Character Countdown - python-3.x

I'm trying to create a function. Function; it will simply be designed to increase the last letter sequence from its position in the alphabet or letter list.
import time
def CountDown(text,reply=3):
abc = list("ABCDEFGHIJ")
c = 1
text_list = list(text)
while 1:
Index = abc.index(text_list[-c])
if not list(filter(lambda a: a!=abc[-1], text_list)):
return "".join(text_list)
if text_list[-c] == abc[-1]:
text_list[-c] = abc[0]
c += 1
continue
else:
s=1
while 1:
text_list[-c] = abc[(Index+s) if (Index+s)<len(abc) else 0]
if text_list.count(abc[(Index+s) if (Index+s)<len(abc) else 0])+1<reply:
break
s+=1
text_list[-c] = abc[(Index+s) if (Index+s)<len(abc) else 0]
return "".join(text_list)
if __name__ == "__main__":
code="ABHD"
while 1:
code=CountDown(code)
time.sleep(0.5)
print(code)
OUTPUT:
ABHE
ABHF
ABHG
ABHI
ABHJ
ABIA
ABIC
ABID
ABIE
ABIF
ABIG
ABIH
ABIJ
ABJA
ABJC
ABJD
ABJE
ABJF
ABJG
ABJH
ABJI
....(idling)
The code doesn't give an output after a while. I think there is something wrong.
How can I fix this code sample?

Related

return does not finish the program in python

Although "if sound_str == None" condition works, the program does not end and keep calling NowYouGotStepSize function. Whats wrong with my return function?
def count_horses(sound_str,outputValue=None):
print("sound_str",sound_str)
stepStr = ""
if sound_str == None:
print("sound_str is =", sound_str)
return True
for eleman in sound_str:
if str(eleman) != "0":
stepStr += "1"works
NowYouGotStepSize(sound_str,stepStr)
else:
stepStr += "0"
Thanks
edit: Some of you asked for full code, It did not finished but still may be you can see the mistake.I am trying to solve this kata. Full Code :
def NowYouGotStepSize(sound_str,stepStr):
arr=[]
arrStep=[]
outputValue = int(len(stepStr))
for eleman in sound_str:
arr.append(eleman)
stepStr = stepStr*len(sound_str)
for eleman in stepStr:
arrStep.append(eleman)
for i in range(0,len(arr)): # horse deleted
arr[i] = int(arr[i])-int(arrStep[i])
stringWithoutaHorse=""
for eleman in arr:
stringWithoutaHorse+=str(eleman)
if int(stringWithoutaHorse) == 0: #are there any 1 after delete horse
return count_horses(None,outputValue) #no means no more horse steps
else:
return count_horses(stringWithoutaHorse, outputValue) #yes means there are another horse
def count_horses(sound_str,outputValue=None):
stepStr = ""
if sound_str == None:
return "12345"
for eleman in sound_str:
if str(eleman) != "0":
stepStr += "1"
NowYouGotStepSize(sound_str,stepStr) #horse step size detected
else:
stepStr += "0"
and input is :
print(count_horses('0212030212')) #output should be [2, 2, 3]

How can I make the program to output the string which both two strings end on in Python?

I have two strings
e.g.
str1 = "Come"
str2 = "Rome"
I want the program to output ome.
How can I do that?
This is what I tried:
def getString(x):
return x
def solve(s1, s2):
a = getString(s1[0])
b = getString(s2[0])
for i in range(1, len(s1)):
if s1[i] != s1[i - 1]:
a += getString(s1[i])
for i in range(1, len(s2)):
if s2[i] != s2[i - 1]:
b += getString(s2[i])
if a == b:
print(a)
return True
return False
Edit: gave a wrong answer. This answer works but not the most efficent, although simple
for i in range(len(a)):
if b.endswith(a[i:]):
print(a[i:])
return

Appending results from a list to a string

Heavy python beginner here. I want to create a simple function for a PIN guessing game that receives two 4-digit lists ( [guess], [answer] ) and returns a string with 4 letters stating how close I am to guessing the correct [answer] sequence (eg. Higher, True, Lower, Higher)
However, I get a new list for each string:
def checkNumbers(guess,right):
for n in range(4):
result = []
if guess[n] == right[n]:
result.append("T") #true
elif guess[n] < right[n]:
result.append("H") #higher
elif guess[n] > right[n]:
result.append("L") #lower
else:
result.append("F") #false
print (result)
return
checkNumbers([1,2,3,5],[2,2,1,6])
The result should look like this:
checkNumbers([1,2,3,4], [2, 2, 1 , 6]) #call function with ([guess], [answer])
'HTLH' #returns a string stating how accurate [guess] is to [answer] list
Result looks like this however:
checkNumbers([1,2,3,5],[2,2,1,6])
['H']
['T']
['L']
['H']
Thanks very much in advance for any help I could get.
you can use string instead of list or "".join()
def checkNumbers(guess, right):
result = ""
for n in range(4):
if guess[n] == right[n]:
result += "T" # true
elif guess[n] < right[n]:
result += "H" # higher
elif guess[n] > right[n]:
result += "L" # lower
else:
result += "F" # false
print(result)
but... maybe you want to use zip function
def checkNumbers(guess, right):
result = ""
for g, r in zip(guess, right):
if g == r:
result += "T" # true
elif g < r:
result += "H" # higher
elif g > r:
result += "L" # lower
else:
result += "F" # false
print(result)
Funny bonus here:
def checkNumbers(guess, right):
print("".join("THL"[(g > r) + (g != r)] for g, r in zip(guess, right)))
I don't get why you need else part...
Initiate the list and print the result outside of the loop:
def checkNumbers(guess, right):
result = []
for n in range(4):
# do loopy stuff
print (result)
return # not strictly necessary
If you do it inside, you are creating a new list on every iteration.

Is there a way i can avoid getting "None" when i print out my function?

I am trying to calculate the avarage grade of a subject. but when i print the function i get printed None.
And i do not know how to fix it.
Ive tried returning the value instead then printing the function, but it wont work.
def karakterKonversjon(bokstav):
if bokstav == 'A':
return 6
if bokstav == 'B':
return 5
if bokstav == 'C':
return 4
if bokstav == 'D':
return 3
if bokstav == 'E':
return 2
if bokstav == 'F':
return 1
def konversjonTilBokstav(tall):
if tall == 6:
return 'A'
if tall == 5:
return 'B'
if tall == 4:
return 'C'
if tall == 3:
return 'D'
if tall == 2:
return 'E'
if tall == 1:
return 'F'
def beregnSnitt():
nummer_karakter = 0
suM = 0
for i in emner:
if emner[i] != "":
tall_karakter = eksamen.karakterKonversjon(emner[i])
suM += (tall_karakter * studiepoeng)
suM /= totalPoeng
rundetSvar = eksamen.normal_round(suM)
eksamen.konversjonTilBokstav(rundetSvar)
print(rundetSvar)
def normal_round(suM):
if (float (suM) < 5):
print(math.floor(suM))
else:
print(math.ceil(suM))
THe result i am expecting is
4
C
But i am getting
4
None
I made a few modifications to your code:
(I assume you are importing math in the eksamen file)
def karakterKonversjon(bokstav): # make this function more efficient
atof = ['A','B','C','D','E','F']
for i in range(len(atof)):
if bokstav.upper() == atof[i]:
return len(atof) - i
def konversjonTilBokstav(tall): # make this function more efficient
atof = ['A','B','C','D','E','F']
for i in range(1,7):
if tall == i:
return atof[len(atof)-i]
def beregnSnitt():
nummer_karakter = 0
suM = 0
for i in range(len(emner)): # if enmer == "enmer"(for example) you cannot reference enmer['e'] without raising an error
if emner[i] != "":
tall_karakter = eksamen.karakterKonversjon(emner[i])
suM += (tall_karakter * studiepoeng)
suM /= totalPoeng
rundetSvar = eksamen.normal_round(suM)
eksamen.konversjonTilBokstav(rundetSvar)
print(rundetSvar)
def normal_round(suM):
if (float (suM) < 5):
print(math.floor(suM))
else:
print(math.ceil(suM))
apart from the differences i made, your code should work well however i cannot test without knowing what enmer is (i assume it's a string) or what studiepoeng is.
the function konversjonTilBokstav did work fine for me. But what I have included in the code snippet should be less spaghetti code

Duplicate word in hangman game Python

I have a problem, when in Hangman game there is a word like happy, it only append 1 'p' in the list...run my code and please tell me what to do?
check my loops.
import random
import time
File=open("Dict.txt",'r')
Data = File.read()
Word = Data.split("\n")
A = random.randint(0,len(Word)-1)
Dict = Word[A]
print(Dict)
Dash = []
print("\n\n\t\t\t","_ "*len(Dict),"\n\n")
i = 0
while i < len(Dict):
letter = str(input("\n\nEnter an alphabet: "))
if letter == "" or letter not in 'abcdefghijklmnopqrstuvwxyz' or len(letter) != 1:
print("\n\n\t\tPlease Enter Some valid thing\n\n")
time.sleep(2)
i = i - 1
if letter in Dict:
Dash.append(letter)
else:
print("This is not in the word")
i = i - 1
for item in Dict:
if item in Dash:
print(item, end = " ")
else:
print("_", end = " ")
i = i + 1
The error is with the "break" on Line 25: once you have filled in one space with the letter "p", the loop breaks and will not fill in the second space with "p".
You need to have a flag variable to remember whether any space has been successfully filled in, like this:
success = False
for c in range(len(Dict)):
if x == Dict[c]:
Dash[c] = x
success = True
if not success:
Lives -= 1
P.S. There's something wrong with the indentation of the code you have posted.

Resources