[英]Error while comparing two strings in python
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
'''
score = 0
tot = len(secretWord)
for i in range(len(secretWord)):
for j in range(len(lettersGuessed)):
if (secretWord[i] == lettersGuessed[j]):
score +=1
if score == tot:
return True
else:
return False
For most of the words and guess letter m getting correct answer but while providing sceretWord as mangosteen
and letter guessed as ['z', 'x', 'q', 'm', 'a', 'n', 'g', 'o', 's', 't', 'e', 'e', 'n']
I am getting wrong output. 对于大多数单词和猜测字母m,它们会得到正确的答案,但同时提供sceretWord作为
mangosteen
和猜测为['z', 'x', 'q', 'm', 'a', 'n', 'g', 'o', 's', 't', 'e', 'e', 'n']
输出错误。
Any suggestions, why? 有什么建议,为什么?
Looks like you could use: 看起来您可以使用:
set(secretWord).issubset(lettersGuessed)
to determine if guessed includes all of the letters in secret word. 确定猜测是否包括秘密单词中的所有字母。
Here is why: 原因如下:
There are two same character in mangosteen
, e
. mangosteen
有两个相同的字符, e
。 Your code encountered it twice, so it adds two score. 您的代码两次遇到它,因此它增加了两个分数。 The total score of when
secretWord[i]
and lettersGuessed[j]
is e
, adds up to 4
. 当
secretWord[i]
和lettersGuessed[j]
是e
, lettersGuessed[j]
为4
。
Here is a solution: 这是一个解决方案:
You can simply use the set
to check if every unique letters is there or not: 您可以简单地使用
set
检查每个唯一字母是否存在:
return all([True if i in set(g) else False for i in set(w)])
This makes the function much shorter :) 这使函数更短:)
Demo: 演示:
>>> g = ['z', 'x', 'q', 'm', 'a', 'n', 'g', 'o', 's', 't', 'e', 'e', 'n']
>>> w = 'mangosteen'
>>> score = 0
>>> all([i for i in set(w) if i in set(g)])
True
An alternative is to break the inner loop straight after you found the wanted letter: 另一种方法是在找到所需字母后直接中断内循环:
if secretWord[i] == lettersGuessed[j]
score +=1
break
Hope this helps! 希望这可以帮助!
My final answer should work with repeated characters, misguessed characters, etc. The key is that each character of the word should be removed from the list of guessed characters; 我的最终答案应该适用于重复的字符,误猜的字符等。关键是单词的每个字符都应从猜中的字符列表中删除; if that fails, the character wasn't guessed (often enough) and we should return False.
如果失败,则不会猜到字符(经常),我们应该返回False。
def isWordGuessed(secretWord, lettersGuessed):
guesses_left = list(lettersGuessed)
for character in secretWord:
try:
guesses_left.remove(character)
except ValueError:
return False # remove failed
return True # all characters succeeded
def isWordGuessed(secretWord, lettersGuessed):
lst = []
for e in lettersGuessed:
if e in secretWord:
lst.append(e)
if len(lst) == len(secretWord):
return True
return False
I did this and it passed all cases. 我做到了,它通过了所有案件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.