检查列表中的两个项是否相同?

时间:2016-03-04 03:07:39

标签: python regex

我的目标:

  

在Lingo的游戏中,有一个隐藏的单词,长五个字符。该   游戏的目的是通过猜测来找到这个词,并作为回报   收到两种线索:1)完全正确的字符,   关于身份和位置,以及2)角色   确实存在于这个词中,但却被置于错误之中   位置。编写一个可以玩Lingo的程序。使用方块   括号在1)和普通的意义上标记正确的字符   括号用于在2)

的意义上标记正确的字符

当前代码:

def lingo():
    import random
    words = ['pizza', 'motor', 'scary', 'motel', 'grill', 'steak', 'japan', 'prism', 'table']
    word = random.choice(words)
    print word
    while True:
        guess = raw_input("> ")
        guess = list(guess.lower())
        word = list(word)
        for x in guess:
            if x in word:
                if x == word[word.index(x)]:
                    guess[guess.index(x)] = "[" + x + "]"
                else:
                    guess[guess.index(x)] = "(" + x + ")"
        print guess

lingo()

截至目前,如果单词共用一个共同的字母,则将该字母放在方括号中,无论它是否共享相同的位置。

示例:

正确: - Word:Table - 我的猜测:Cater - 输出:C[a](t)(e)r

不正确的: - Word:Japan - 我的猜测:Ajpan(注意a和j之间的切换,我是故意这样做的)。 - 输出:[A][j][p][a][n](应为(a)(j)[p][a][n]

2 个答案:

答案 0 :(得分:6)

您的错误就在这一行:

if x == word[word.index(x)]:

始终为真,因为word[word.index(x)]x相同。尝试将其更改为:

if x == word[guess.index(x)]:

答案 1 :(得分:3)

if x == word[word.index(x)]:应为if x == word[guess.index(x)]:

相关问题