python - Sum of numbers in array, not counting 13 and number directly after it (CodingBat puzzle) -
python - Sum of numbers in array, not counting 13 and number directly after it (CodingBat puzzle) -
the question:
return sum of numbers in array, returning 0 empty array. except number 13 unlucky, not count , numbers come after 13 not count.
my code:
def sum13(nums): l = len(nums) tot = 0 if l==0: homecoming 0 x in range(l): if nums[x]!=13: if nums[x-1]!=13: tot+=nums[x] homecoming tot
where it's failing:
sum13([1, 2, 2, 1, 13]) should → 6, code outputting 5 sum13([1, 2, 13, 2, 1, 13]) should → 4, code outputting 3
your problem when x
zero. x - 1
-1
lastly element of list (13
). prepare it, don't test x - 1
if x
zero:
if x == 0 or nums[x-1] != 13:
in python, when pass negative index list accesses elements backwards, so:
>>> x = [1,2,3,4,5] >>> x[-1] 5 >>> x[-2] 4
python list
Comments
Post a Comment