因此,在与字符列表进行比较后,我的代码应该理想地打印出不完整的单词。
例如,如果单词是stackoverflow并且列表包含's','a','k', 'o', 'r','l'
,则输出应为
s _ a _ k o _ _ r _ l o _
我的代码是
def getGuessedWord(secretWord, lettersGuessed):
'''
secretWord: string, the word the user is guessing
lettersGuessed: list, what letters have been guessed so far
returns: string, comprised of letters and underscores that represents
what letters in secretWord have been guessed so far.
'''
i=0
gameWord=''
while i in range(len(secretWord)):
if(i%2!=0):
gameWord+=' ' #to print spaces between characters
else:
if(secretWord[i] in lettersGuessed):
gameWord+=secretWord[i]
else:
gameWord+='_'
return gameWord
但我的代码只是挂起!我无法弄清楚为什么!
答案 0 :(得分:0)
您需要确保增加变量i。否则,你无限循环你的while循环!
循环时在循环内部的底部添加i ++。
这将解决您的无限循环问题,但不会为您提供您正在寻找的预期输出。你需要重新修改你的if / else逻辑,你就得到了它。
答案 1 :(得分:0)
你的循环如果是无限循环因此它会挂起(因为i = 0总是在你的范围内)。
看起来你需要这样:
def getGuessedWord(secretWord, lettersGuessed):
'''
secretWord: string, the word the user is guessing
lettersGuessed: list, what letters have been guessed so far
returns: string, comprised of letters and underscores that represents
what letters in secretWord have been guessed so far.
'''
gameWord=''
for c in secretWord:
if c in lettersGuessed:
gameWord += c
else:
gameWord += '_'
return gameWord
print(getGuessedWord('stackoverflow', ['s','a','k', 'o', 'r','l']))
输出:
s_a_ko__r_lo _
但如果你真的想要你的方式:
def getGuessedWord(secretWord, lettersGuessed):
'''
secretWord: string, the word the user is guessing
lettersGuessed: list, what letters have been guessed so far
returns: string, comprised of letters and underscores that represents
what letters in secretWord have been guessed so far.
'''
i=0
gameWord=''
while i in range(len(secretWord)):
gameWord += ' '
if(secretWord[i] in lettersGuessed):
gameWord += secretWord[i]
else:
gameWord += '_'
i += 1
return gameWord