There is an error in your program. Check the results:
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 7 immediately follows 6, you add 6 and all of the following numbers. I'm not sure that more than one range of 6 ... 7 is allowed at the input, but if so, you should fix your algorithm.
This simple implementation returns the 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
In addition, if you do not need to use the index for some unclear reasons, you can directly iterate over the list items ( for element in list: ...
).
hochl source share