python - 如何按顺序显示单词猜测器的猜测字母?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)
解决方案
您应该迭代单词,以便输出正确单词中字母的单词中的猜测字母。使用一个集合来跟踪正确的字母以进行有效的查找,因为您只需要它来确定一个字母是否被正确猜到:
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
推荐阅读
- c# - Gridview 行颜色基于 GridView 外部的文本框值
- kubernetes - CORS 规则 nginx-ingress 规则
- r - 根据另一个数据框中的日期范围划分数据框中的值
- ajax - 在 CakePHP 3.6 中使用 ajax 上传图像时 CSRF 令牌不匹配
- android - 来自 URL 的音频流无法从数据源初始化?
- google-bigquery - 当字段包含@sign BigQuery Standard SQL时,我如何使用函数从Google BigQuery中提取json
- android - 未知类:AndroidX 双向数据绑定中的 java.lang.String
- wordpress - wp简单会员插件同时登录
- c++ - 将任何类型的对象的函数传递给 C++ 中的另一个对象
- linux - 使用 Qt 使用 cc2564moda 在 beagleboneblack 上配置蓝牙