2014-02-26 33 views
0

我正在嘗試編寫一個程序,我可以在其中輸入一個列表,如果列表中的所有值相等,它將返回布爾型Yahtzee爲True。當我運行它時,它可以在99%的時間內運行。但是,索引3可能與列表中的其他值不同,並且isYahtzee()仍然會將Yahtzee返回爲True。有人可以幫我調試嗎?檢查列表中的值是否相等返回錯誤結果

#Determine whether all of them are the same and returns a Boolean. 
def isYahtzee(aList): 
    #This tells the program to look down the entire length of the list   
    for i in range (0,len(aList)): 
    #Since I will be working with a list with no more than 5 numbers, I se 
     #This equal to 5 indexs (0-4) 
     if aList[0] == aList[1] and aList[1] and aList[2] and aList[3] and aList[4]: 
      #If all of them are equal, the boolean Yahtzee = True 
      Yahtzee = True 

     #If they are not all equal to eachother  
     if aList[0] != aList[i]: 
      #The Boolean Yahtzee = False 
      Yahtzee = False 

    #Return the value of the Boolean   
    return Yahtzee 

回答

2

你可以檢查,看看如果列表長度爲5,如果列表的set是長度1

#Determine whether all of them are the same and returns a Boolean. 
def isYahtzee(aList): 
    return (len(aList) == 5 and len(set(aList)) == 1) 

話雖這麼說,你的問題是,你只爲測試等於aList[0] == aList[1] - and aList[1] and aList[2] and aList[3] and aList[4]段只會檢查以確保其他值存在,而不是它們等於aList[0]

如果您想使其更加嚴格,您還可以添加and all(isinstance(item, int) for item in aList)以檢查所有值是整數,並且爲了檢查所有值是否爲有效(標準)模值,請輸入and max(aList) <= 6 and min(aList) >= 1

0

我會採取稍微不同的方法,以避免在您不需要昂貴的set時構建。

def isYahtzee(aList): 
    return all(item==aList[0] for item in aList) 

這將需要兩個項目沒有爲等效測試True時,他們實際上並不相同,但除非你正在構建自定義類的骰子,包括那些(而不是他們所生產的模輥)在你的list中,這不應該是這個實現中的問題。