这是edx python编程中的一个问题。 它有一个我无法弄清楚的错误。 基本上,逻辑是如果密码等于猜测密码,则增加计数。 在以下情况下,我有意放置一个空列表来测试代码。在第一次运行期间,很明显['']不等于'a',但是代码仍然执行if语句。 我想念什么吗? 谢谢。
def isWordGuessed(secretWord, lettersGuessed):
'''
secretWord: string, the word the user is guessing
lettersGuessed: list, what letters have been guessed so far
returns: boolean, True if all the letters of secretWord are in lettersGuessed;
False otherwise
'''
count = 0
tempList = []
for element in lettersGuessed:
if element in secretWord and element not in tempList: #to avoid re-counting repetitive char that matches with string
count += 1
tempList.append(element)
if count == len(secretWord):
return True
else:
return False
print(isWordGuessed('a',['']))
答案 0 :(得分:2)
if
是True
您的if
语句被评估为True
,因为'' in 'put_any_string_here'
始终为True
空字符串始终是其他字符串的子字符串
def is_word_guessed(secret_word, letters_guessed):
l = list(filter(lambda c: c in letters_guessed, list(secret_word)))
return ''.join(l) == secret_word