用Python编写的Mastermind / Bulls and Cows游戏checkguess

时间:2014-05-21 17:50:10

标签: python

我发现我的功能有2个问题可以检查我的猜测。

1)假设代码是[2,3,4,5]和[0,0,0,2],我认为正确的响应应该是0B 1C,但我得到的是0B 3C。

2)当我输入[0,0,0,0]作为猜测时,我得到一个索引错误,'列表索引超出范围'。 = [不知道为什么。

我的代码如下:

def checkGuess1(code, guess):
    i = 0
    countB = 0
    countC = 0
    while i < len(code):
        if code[i] == guess[i]:
            countB = countB + 1
        else:
            for j in code:
                if code[i] == guess[j] and i != j :
                    countC = countC + 1
        i = i + 1

    print "A: " + str(countB)
    print "B: " + str(countC)
    return countB, countC

#------------- TEST CASE -----------------------
code = [2,3,4,5]
guess = [0,2,2,2]
guess1 = [0,0,0,0]
checkGuess1(code, guess)
checkGuess1(code, guess1)

感谢您的时间和帮助!小心!

1 个答案:

答案 0 :(得分:1)

你的问题在这里

for j in code:

这会迭代代码中的元素...而不是索引...但后来你说

if code[i] == guess[j] and i != j : 
              ^ 
              j will be 2, then 3,then 4, then 5 ... guess has no indice 4 or 5

然而,您可以更好地实现这一切,如下所示

def checkGuess(code,guess):
    bulls = sum(c1==c2 for c1,c2 in zip(code,guess))
    cows =  sum(c1 != c2 and c2 in code for c1,c2 in zip(code,guess))
    return bulls,cows

更好的代码可以做到这一点

这是一个实现,可以更清楚地了解发生了什么

def  checkGuess(code,guess):
     bulls = cows = 0 # no bulls or cows yet
     for code_char,guess_char in zip(code,guess): #pairs up the letters
         if code_char == guess_char: #match , bull
            bulls = bulls + 1
         elif guess_char in code:# no match but the item is in the code, cow
            cows = cows + 1
     return bulls,cows

print checkGuess("1234","5464")
#or
print checkGuess([1,2,3,4],[4,4,4,4])