0
def validateGuess():
    print(letters)
    inputGuess= input("Choose one of the letters above:")
    return inputGuess

def wordLength():
    length=input("Welcome to Hangman. How many letters in the secret word?")
    length1=int(length)
    if length1 <0:
        length=input("Welcome to Hangman. How many letters in the secret word?")
    return length    

def guessAmount():
    guesses=input("How many guesses would you like?")
    guesses1=int(guesses)
    if guesses1 < 0:
        guesses=input("How many guesses would you like?")
    return guesses

welcome=wordLength()
remain=input("Do you want to print the count of how many words remain [Y/N]?")
guessNumber=int(guessAmount())
F=open('dictionary.txt')
F1=F.readlines()

welcome2=int(welcome)
a_list=[word.strip('\n') for word in F1]
possible_words = [x for x in a_list if len(x) == welcome2]

letters= ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']

while guessNumber >0:
    letter_guess=validateGuess()
    letters.remove(letter_guess)
    guessNumber -= 1
    result={}
    for word in possible_words:
        key=' '.join(letter_guess if c == letter_guess else '-' for c in word)
        if key not in result:
            result[key]=[]
        result[key].append(word)
    inverse= [(len(value), key) for key, value in result.items()]
    Answer=max(inverse)[1]
    possible_words=result.values()
    print()

我正在用 Python 编写一个名为 Evil Hangman 的程序。基本上,给定一个 170,000 个单词的列表,我必须尽可能让用户获胜。所以对于每个用户的猜测,比如“A”,我根据“A”在单词中出现的位置将单词放入族中,然后选择最大的族并打印“A”在该族中出现的位置。无论用户决定多久,这都会持续下去。我的问题是我想不出一种方法来为我的 while 循环创建一个新的单词列表。这个新列表将只包含最大家族中的单词。我想,

for word in max(result):
     possible_words+=word

会起作用,但我不知道为什么它不起作用。非常感谢任何和所有帮助。另外,我是 Python 的新手,并且尽我所能解释了我的问题,但是如果您有任何问题,请不要犹豫。

4

1 回答 1

1

通过查看代码,您似乎可以从此更改 while 循环的结尾:

Answer=max(inverse)[1]
possible_words=result.values()

对此:

Answer=max(inverse)[1]
possible_words=result[Answer]

因为Answerwill be the key from resultthat 给你最大的家庭,result[Answer]将是那个最大的家庭,你可以重新分配possible_words给那个值。

于 2013-04-12T18:51:07.447 回答