CodingBat sum67: why is this solution wrong?

Below is my solution for your reference:

def sum67(nums):
flag=False
sum=0

for num in nums:
    if(num==6):                  #Turn the flag on if the number is 6
        flag=True
        continue
    if(num==7 and flag is True): #Turn the flag Off when 7 is seen after 6
        flag=False
        continue
    if(flag is False):           #Keep on adding the nums otherwise
       sum+=num
return sum

Well, your program has a bug. Check the results of the following:

print sum67([1,2,5])
print sum67([1,2,6,5,7])
print sum67([1,2,6,5,7,6,7])

This will print:

8
3
16 <-- wrong

If a 7 is followed by a 6 immediately, you will add the 6 and all following numbers. I'm not sure if more than one range of 6 ... 7 is allowed in the input, but if it is, you have to fix your algorithm.

This simple implementation does return correct numbers:

def sum67(nums):
        state=0
        s=0
        for n in nums:
                if state == 0:
                        if n == 6:
                                state=1
                        else:
                                s+=n
                else:
                        if n == 7:
                                state=0
        return s

Besides, if you don't need to use an index for some obscure reasons, you can directly iterate over the elements of a list ( for element in list: ... ).

Tags:

Python