Interesting... I tried your code seems fine, but it will not behave as you want though...
I tried this:
def sum13(nums):
sum = 0
if nums[0] != 13:
sum += nums[0]
for i in range(len(nums)):
print 'Current number:', str(nums[i])
print 'Previous number:', str(nums[i-1])
if nums[i] != 13 and nums[i - 1] != 13:
sum += nums[i]
return sum
ls = [10,11,13,12,14,14]
print 'Total sum:', str(sum13(ls))
returned 59, it was supposed to be (10+11+14+14) = 49.
Why this occurred? It's because you check in the loop nums[i-1].
Since i = 0 in the first loop, i-1 = -1. So, nums[-1] is the last item in your list.
Can you have a try and test this small test?
One way to fix this issue is:
def sum13(nums):
sum = 0
if nums[0] != 13:
sum += nums[0]
for i in range(1, len(nums)):
print 'Current number:', str(nums[i])
print 'Previous number:', str(nums[i-1])
if nums[i] != 13 and nums[i - 1] != 13:
sum += nums[i]
return sum
ls = [10,11,13,12,14,14]
print 'Total sum:', str(sum13(ls))
If it still not working can you share your code and your test?
As mentioned in the comments:
def sum13(nums):
if nums:
sum = 0
if nums[0] != 13:
sum += nums[0]
for i in range(1, len(nums)):
print 'Current number:', str(nums[i])
print 'Previous number:', str(nums[i-1])
if nums[i] != 13 and nums[i - 1] != 13:
sum += nums[i]
return sum
if not nums:
print 'Empty list'
ls = [10,11,13,12,14,14]
print 'Total sum:', str(sum13(ls))
ls2 = []
print sum13(ls2)
Cheers,