0

I'm trying to return the sum of the numbers in the array, returning 0 for an empty array. Except the number 13 it doesn't count and the number immediately after 13.

def sum13(nums):
  p = 0
  for i in range(len(nums)):
    if nums[i] == 13 and nums[i + 1]:
      continue
    p += nums[i]
  return p

When I run it, it gives me an index error list index our of range, what am I doing wrong?

T Tse
  • 786
  • 7
  • 19
Pou Conect
  • 31
  • 5

4 Answers4

2

Here is what you want:

def sum13(nums):
    p = 0
    skip_next = False
    for i in range(len(nums)):
        if nums[i] == 13:
           skip_next = True
           continue
        if skip_next:
            skip_next = False
            continue
        p += nums[i]
    return p
emilaz
  • 1,722
  • 1
  • 15
  • 31
1

range(len(nums))'s size is the same size of nums.
Hence, doing nums[i+1] doesn't exist.

ggrelet
  • 1,071
  • 7
  • 22
0

if nums[i]==13 and nums[i+1] won't work, since i+1 will be bigger than the length of the list, also nums[i]+1 just checks if the number exists, it doesn't skip it.
You want to skip a number if it is 13, or the number before it is 13, as follows

def sum13(nums):

    p = 0
    for i in range(len(nums)):
        if nums[i] == 13 or nums[i-1] == 13:
            continue
        else:
            p += nums[i]
    return p

print(sum13([1,2,13,14,5,6,7]))
#21
print(sum13([13,14]))
#0
print(sum13([13]))
#0
print(sum13([]))
#0
Devesh Kumar Singh
  • 20,259
  • 5
  • 21
  • 40
0

The problem is with nums[i+1], it is out of the range of your list. Here is another solution using while.

def sum13(nums):
    p=0; i=0
    while i < len(nums):
        if nums[i]==13:
            i = i + 2 #exclude the position after 13
            continue
        else:
            p+=nums[i]
            i=i+1
    return p
ivanc
  • 16
  • 1
  • 3