0

所以我的一段代码最好在与字符列表比较后打印出不完整的单词。

例如,如果单词是 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

但我的代码只是挂起!我不知道为什么!

4

2 回答 2

0

您需要确保增加变量 i。否则,您将无限循环您的 while 循环!

在循环的底部添加 i++ while 循环。

这将解决您的无限循环问题,但不会为您提供您正在寻找的预期输出。你需要重新设计你的 if/else 逻辑并且你已经掌握了。

于 2013-11-02T13:04:38.240 回答
0

你的循环 if neverending loop 因此它挂起(因为 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
于 2013-11-02T13:06:46.017 回答