Wiggs Wiggs - 4 months ago 12
Python Question

Count the number of times each element appears in a list. Then making a conditional statement from that

write a function that takes, as an argument, a list called aList. It returns a Boolean True if the list contains each of the integers between 1 and 6 exactly once, and False otherwise.

This is homework and I thought I had it right, but it is now telling me that it isn't right. Here is my code.

def isItAStraight(aList):
count = 0
for i in set(aList):
count += 1
return aList.count(i) == 1

for some reason even if a number appears more than once it still gives true and I can't figure out why it won't give me false unless the first or last number are changed.

Each number has to occur only one time otherwise it is false.

So like take [1,2,3,4,5,6]
would be true.
But [1,2,2,3,4,5]
would be false.

Also, I can't import things like Counter or collections (though it would be so much easier to do it isn't apart of the assignment.)

The list is randomly generated from 1 to 6.


With a return inside the loop, you are only checking one value. You need to check each value. Also, instead of looping through the items of the list, you should loop through the items you're actually looking for. It would also help to make sure there are the correct number of items in the list.

def isItAStraight(aList):
    if len(aList) != 6:
        return False
    for i in range(1, 7):
        if aList.count(i) != 1:
            return False
    return True

But the easiest way to do this is to simply sort the list and check if it's what you're looking for:

def isItAStraight(aList):
    return sorted(aList) == list(range(1, 7))