首页 > 解决方案 > 如何按顺序显示单词猜测器的猜测字母?Python

问题描述

我被要求在 python 中创建一个单词猜测器,它向用户输出单词中有多少个字母,例如 python 有 6 个,所以它会输出 6。然后用户有 5 个猜测来猜测单词中有哪些字母单词,在这 5 次猜测之后,用户应该猜测单词。我已经能够通过将它们连接到一个新字符串来显示正确猜测的字母,但是我无法显示单词的正确位置,并且如果字母在单词中出现两次,基本上就像刽子手.

问题 1:我怎样才能让猜到的字母按照单词的顺序出现,而不是按照它们被猜到的顺序出现?

问题 2:我如何让一个重复的字母在单词中出现多次?

下面的代码:

#WordGuesser

import random

WORDS = ("computer","science","python","pascal","welcome")

word = random.choice(WORDS)
correctLetters = ""
guesses = 0

print(
    """

    Welcome to Word Guesser!
    You have 5 chances to ask if a certain letter is in the word
    After that, you must guess the word!

    """
)

print("The length of the word is", len(word))


while guesses != 5:
    letter = input("Guess a letter: ")

    if letter.lower() in word:
        print("Well done", letter, "is in the word")
        correctLetters += letter
        print("Correctly guessed letters are: ",correctLetters)
        guesses += 1


    else:
        print("No", letter, "is not in the word")
        correctLetters += "-"
        guesses += 1

guess = input("Please now guess a word that it could be!: ")

if guess == word:
    print("Well done, you guessed it")
    input("\n\nPress enter key to exit")

else:
    ("You did not guess it, the word was: ",word)

标签: pythonpython-3.x

解决方案


您应该迭代单词,以便输出正确单词中字母的单词中的猜测字母。使用一个集合来跟踪正确的字母以进行有效的查找,因为您只需要它来确定一个字母是否被正确猜到:

correctLetters = set()
while guesses != 5:
    letter = input("Guess a letter: ").lower()

    if letter in word:
        print("Well done", letter, "is in the word")
        correctLetters.add(letter)
        print("Correctly guessed letters are: ", ''.join(letter if letter in correctLetters else '-' for letter in word))

    else:
        print("No", letter, "is not in the word")
    guesses += 1

演示:https ://repl.it/@blhsing/WellmadeAlarmingInformation


推荐阅读