Skip to content
Advertisement

Sum of numbers in array, not counting 13 and number directly after it (CodingBat puzzle)

The Question:

Return the sum of the numbers in the array, returning 0 for an empty array. Except the number 13 is very unlucky, so it does not count and numbers that come immediately after a 13 also do not count.

My Code:

def sum13(nums):
  l = len(nums)
  tot = 0

  if l==0:
    return 0

  for x in range(l):
    if nums[x]!=13:
      if nums[x-1]!=13:
        tot+=nums[x]

  return tot

Where It’s Failing:

sum13([1, 2, 2, 1, 13]) should → 6, but my code is outputting 5
sum13([1, 2, 13, 2, 1, 13]) should → 4, but my code is outputting 3

Advertisement

Answer

Your problem is when x is zero. x - 1 will be -1 so it will get the last element of your list (13). To fix it, don’t test x - 1 if x is zero:

if x == 0 or nums[x-1] != 13:

In Python, when you pass a negative index to a list it accesses its elements backwards, so:

>>> x = [1,2,3,4,5]
>>> x[-1]
5
>>> x[-2]
4
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement