Why doesnt my Python function print to console? - python

I can't seem to figure out why my function doesn't print anything when called.
This is the function (and a list that's used in the function):
old_letters = ['a', 'p', 'c', 'f']
def try_update_letter_guessed(letter_guessed, old_letters_guessed):
length = len(letter_guessed)
english_validation = letter_guessed.isalpha()
already_used = letter_guessed in old_letters_guessed
if (length > 1) or (english_validation == False) or (already_used == True):
print("X")
delim = "->"
res = delim.join(sorted(old_letters_guessed))
print(res)
return False
elif (length == 1) and (english_validation == True) and (already_used == False):
old_letters_guessed.append(letter_guessed)
return True
However, when I call my function (with arguments) like so:
try_update_letter_guessed('A', old_letters)
it doesn't print anything at all.
What am I missing?

When letter_guessed is 'A', then (length > 1) or (english_validation == False) or (already_used == True) is not true, so this goes to the elif, and that doesn't print anything.
If you try with arguments which will make that condition true, then it does print:
>>> try_update_letter_guessed('AB', old_letters)
X
A->a->c->f->p
False
>>> try_update_letter_guessed('a', old_letters)
X
A->a->c->f->p
False

Use print() inside the elif block. Because the argument 'A' will only lead into the elif block so after appending to the old_letters_guessed if you want to see something in the console use the print() function.

Related

What's wrong with recursive Regex function code in python

I wrote a regex code which compares two strings. It recognises a special character '?' that allows zero or more instances of previous character. It works fine until there are two or more occasions of '?' in the string. And I can't make out why.
def single_character_string(a, b) -> "return True if characters match":
"""check if two characters match"""
if len(a) == 0:
return True
elif len(b) == 0:
return False
else:
if a == '.':
return True
else:
if a == b:
return True
else:
return False
def meta_question_result(temp):
if len(temp) >= 2:
if temp[1] == '?':
k_1 = temp.replace(temp[0: 2], '') # no char
k_2 = temp.replace(temp[1], '') # char
return k_1, k_2
def check_pair_by_pair(template, check_string) -> "Strings are of Equal length! " \
"return True if lines are identical":
"""check if two strings match symbol by symbol. template may be less than string, the opposite
is False"""
if not template: # exit from recursion
return True
if not check_string: # exit from recursion
return False
if meta_question_result(template):
t_1, t_2 = meta_question_result(template)
if single_character_string(t_1[0], check_string[0]):
return check_pair_by_pair(t_1[1:], check_string[1:])
if single_character_string(t_2[0], check_string[0]):
return check_pair_by_pair(t_2[1:], check_string[1:])
else:
return False
elif single_character_string(template[0], check_string[0]):
return check_pair_by_pair(template[1:], check_string[1:])
else:
return False
reg, st = input().split("|")
print(check_pair_by_pair(reg, st))
reg = "co?lou?r"
st = "colour"
gives True as expected,
reg = "co?lou?r"
st = "clor"
gives True as expected,
but...
reg = "co?lou?r"
st = "color"
gives False. I expected True.
Found the bag.
Replace method replaces all instances of '?'. So the second '?' was replaced also and program didn't see it.
I should add an argument 'count' to replace method that is equal to 1.
k_1 = temp.replace(temp[0: 2], '', 1) # no char

Python: A function to check the last string

the function takes user's input (a string). It should return True if the last character appears more than once in the string, regardless if it's upper or lower case, otherwise it returns False.
What is wrong with the code?
def last_early(word):
word.lower()
if word.count(word[-1]) > 1:
print("True")
else:
print("False")
This is what I expect:
>>> last_early("happy birthday")
True
>>> last_early("best of luck")
False
>>> last_early("Wow")
True
>>> last_early("X")
False
Try:
def last_early(word):
lower_word = word.lower() # word.lower won't change word itself
if lower_word.count(lower_word[-1]) > 1:
return True
else:
return False
you can test by running:
def testLastEarly():
print("testing last_early()...",end="")
assert(last_early("happy birthday") == True)
assert(last_early("best of luck") == False)
assert(last_early("Wow") == True)
assert(last_early("X") == False)
print("pass")
testLastEarly()
if you want to try more exercise, check out here

How do You change a variable to a string in python?

So I am trying to change a randomized variable to a string with a function, any ideas why this isn't working?
def letter(x):
if x == 1:
x = "A"
elif x == 2:
x = "C"
elif x == 3:
x = "G"
elif x == 4:
x = "T"
else:
print "Error"
randint18= random.randrange(1,5)
letter(randint18)
print randint18 `
You have to return the value from the function, and assign it to a variable.
def letter(x):
...
return x
randint18 = random.randrange(1, 5)
result = letter(randint18)
print result
mine isn't a proper answer, which have been provided already, but a suggestion for improving your code. I'd do it in a comment, but the code formatting ain't good enough.
Why not use a dictionary for the mapping, instead of a sequence of if's? You could still place it in a function if you like:
letter = {1:'A', 2:'C', 3:'G', 4:'T'}
randint18 = random.randrange(1,5)
mapping = letter.get(randint18, 'Error')
print mapping
mind you, a list would be even more efficient, if the mapping started form zero:
letter = ['A', 'C', 'G', 'T']
randint18 = random.randrange(0,4)
try: # in case your random index were allowed to go past 3
mapping = letter[randint18]
except IndexError:
mapping = 'Error'
print mapping
You cannot alter the variable in place you must return it and capture the returned value.
import random
def letter(x):
if x == 1:
x = "A"
elif x == 2:
x = "C"
elif x == 3:
x = "G"
elif x == 4:
x = "T"
else:
print "Error"
return x # return it here
randint18= random.randrange(1,5)
randint18 = letter(randint18) # capture the returned value here
print randint18
There is a simpler way to achieve what you want, using a dictionary to map the values.
import random
def letter(x):
mapd = {1:'A', 2:'C', 3:'G', 4:'T'}
return mapd.get(x, None)
randint18= random.randrange(1,5)
randint18 = letter(randint18)
print randint18
You forgot to include a return in your function
def letter(x):
if x == 1:
x = "A"
elif x == 2:
x = "C"
elif x == 3:
x = "G"
elif x == 4:
x = "T"
else:
print "Error"
return x
randint18 = random.randrange(1,5)
returned_result = letter(randint18)
print returned_result
Add a return value of the function
return x
value_you_want = letter(randint18) ##add the return statement. Output will be saved to value_you_want
Please note that the variables defined inside a function are local to the function and cannot be accessed outside the scope of the function. You were expecting the value of x outside the function which is not possible. Just to check run your function and try to access the value in variable x. It will give error.
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
print x
NameError: name 'x' is not defined

Why does my Python recursive function not break?

I have this code that should break once it fulfills a certain condition, ie when the isuniquestring(listofchar) function returns True, but sometimes it doesn't do that and it goes into an infinite loop. I tried printing the condition to check if there's something wrong with the condition, but even when the condition is printed true the function still continues running, I have no idea why.
one of the strings that throws up an infinite loop is 'thisisazoothisisapanda', so when I do getunrepeatedlist('thisisazoothisisapanda'), it goes into an infinite loop.
would be really grateful if someone could help
thanks!
Here's my code:
def getunrepeatedlist(listofchar):
for ch in listofchar:
if isrepeatedcharacter(ch,listofchar):
listofindex = checkrepeatedcharacters(ch,listofchar)
listofchar = stripclosertoends(listofindex,listofchar)
print (listofchar)
print (isuniquestring(listofchar))
if isuniquestring(listofchar):
return listofchar
#print (listofchar)
else:
getunrepeatedlist(listofchar)
return listofchar
just for reference, these are the functions I called
def isrepeatedcharacter(ch,list):
if list.count(ch) == 1 or list.count(ch) == 0:
return False
else:
return True
def checkrepeatedcharacters(ch,list):
listofindex=[]
for indexofchar in range(len(list)):
if list[indexofchar] == ch:
listofindex.append(indexofchar)
return listofindex
def stripclosertoends(listofindices,listofchar):
stringlength = len(listofchar)-1
if listofindices[0] > (stringlength-listofindices[-1]):
newstring = listofchar[:listofindices[-1]]
elif listofindices[0] < (stringlength-listofindices[-1]):
newstring = listofchar[listofindices[0]+1:]
elif listofindices[0] == (stringlength-listofindices[-1]):
beginningcount = 0
endcount = 0
for index in range(listofindices[0]):
if isrepeatedcharacter(listofchar[index],listofchar):
beginningcount += 1
for index in range(listofindices[-1]+1,len(listofchar)):
if isrepeatedcharacter(listofchar[index],listofchar):
endcount += 1
if beginningcount < endcount:
newstring = listofchar[:listofindices[-1]]
else:
#print (listofindices[0])
newstring = listofchar[listofindices[0]+1:]
#print (newstring)
return newstring
def isuniquestring(list):
if len(list) == len(set(list)):
return True
else:
return False
It may be due to the fact that you are changing listofchar in your for loop. Try cloning that variable to a new name and use that variable for manipulations and return the new variable.

How is my variable not defined?

Currently, what I have is
ntries = 0
def test_guess(code,guess):
if guess == code:
return True
ntries += 1
else:
return False
blackpegs = 0
whitepegs = 0
code_remainder = ''
guess_remainder = ''
ntries += 1
for x, y in zip(code,guess):
if x==y:
blackpegs += 1
elif not x==y:
code_remainder += x
guess_remainder += y
for i in guess_remainder:
if code_remander.find(i) != -1: #if i is found in the remainder of the code
whitepegs += 1
code_remainder = code_remainder.replace(i, 'X', 1)
return code_remainder
return guess_remainder
return blackpegs
return whitepegs
Right below, I have
if test_guess(code,guess)==True:
print 'You won!"
elif test_guess(code,guess)==False:
print 'Not quite. You get',blackpegs,'black pegs,',whitepegs,'white pegs.'
blackpegs in my final print statement keeps coming up as undefined. Why is it not set to be equal to the blackpegs counter?
if guess == code:
return True
ntries += 1
if your guess == code, then return true, next step can't be executed!
You can only have one return statement.
return code_reminder
Causes the function to immediately exit. You will want to do something like
return code_remainder, guess_remainder, blackpegs, whitepegs
and then when you call the function, use:
code_remainder, guess_remainder, blackpegs, whitepegs = test_guess(code,guess)
General Tip:
Variables/references declared within a function only exist within that function. You will need to explicitly return those variables/references if you want to use them outside of the function. Of course there are also some exceptions to this rule, but it is best that you stick to this method for now.
blackpegs doesn't have a value unless the else statement is reached. i.e. if guess == code, blackpeg is not defined.
It needs to be set to zero before the if else statements or otherwise addressed prior to being called in the return statement.

Categories