0

I'm trying to write a program in which I can input a list and if all the values in the list are equal, it returns the boolean Yahtzee as True. When I run it, it works 99% of the time. However, index 3 can be different than the other values in the list and isYahtzee() will still return Yahtzee as True. Can someone help me debug this?

#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 
DreadPirateShawn
  • 8,164
  • 4
  • 49
  • 71

2 Answers2

2

You could check to see if the list is length 5 and if the set of the list is length 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)

That being said, your problem is that you're only testing for equality of aList[0] == aList[1] -- the and aList[1] and aList[2] and aList[3] and aList[4] segment only checks to make sure that the other values exist, not that they are equal to aList[0].

If you wanted to make it more strict, you could also add and all(isinstance(item, int) for item in aList) in order to check that all values are integers, and and max(aList) <= 6 and min(aList) >= 1 in order to check if all the values are valid (standard) die values.

DreadPirateShawn
  • 8,164
  • 4
  • 49
  • 71
0

I would take a slightly different approach, to avoid an expensive set build when you don't need one.

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

This will require that two items don't test True for equivalency when they're not actually the same, but unless you're building custom classes for dice and including those (rather than the die rolls they produce) in your list, it shouldn't be an issue in this implementation.

Adam Smith
  • 52,157
  • 12
  • 73
  • 112