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:
JavaScript
x
14
14
1
def sum13(nums):
2
l = len(nums)
3
tot = 0
4
5
if l==0:
6
return 0
7
8
for x in range(l):
9
if nums[x]!=13:
10
if nums[x-1]!=13:
11
tot+=nums[x]
12
13
return tot
14
Where It’s Failing:
JavaScript
1
3
1
sum13([1, 2, 2, 1, 13]) should → 6, but my code is outputting 5
2
sum13([1, 2, 13, 2, 1, 13]) should → 4, but my code is outputting 3
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:
JavaScript
1
2
1
if x == 0 or nums[x-1] != 13:
2
In Python, when you pass a negative index to a list it accesses its elements backwards, so:
JavaScript
1
6
1
>>> x = [1,2,3,4,5]
2
>>> x[-1]
3
5
4
>>> x[-2]
5
4
6