Reputation: 1
Write a function sum13(nums) that takes a list of ints nums and returns the sum of the numbers in the list, returning 0 for an empty list. Except the number 13 is very unlucky, so it does not count and numbers that come immediately after a 13 also do not count.
Test Result
print(sum13([1, 2, 2, 1, 13]))
6
print(sum13([13, 2, 2, 1]))
3
print(sum13([13, 13, 2, 13, 1, 5, 6, 13]))
11(EXPECTED)
13(GOT)
here is my program I don't know why the last test code is not running
def sum13(nums):
"""jdhdjkls"""
if len(nums) == 0:
return 0
for i in range(0, len(nums)):
if nums[i] == 13:
nums[i] = 0
if i+1 < len(nums):
nums[i+1] = 0
return sum(nums)
Upvotes: 0
Views: 225
Reputation: 158
Your scripts can't correspond to 13 13 2
because they are made 0 0 2
in first step.
for
and continue
is effective for your goal.
def sum13(nums):
sums=0
after13=False
for num in nums:
if num == 13:
after13=True
continue
if not after13:
sums+=num
after13=False
return sums
Upvotes: 0
Reputation: 41905
We could try using recursion to solve this problem:
def sum13(numbers):
if not numbers: # base case
return 0
first, *rest = numbers
if first == 13:
first = 0
if rest and rest[0] != 13:
rest.pop(0)
return first + sum13(rest)
print(sum13([1, 2, 2, 1, 13]))
print(sum13([13, 2, 2, 1]))
print(sum13([13, 13, 2, 13, 1, 5, 6, 13]))
Though not the style of answer you likely want, we can also coerce itertools.groupby
to do the work for us:
from itertools import groupby
def sum13(numbers):
previous13 = False
def is_tainted(number):
nonlocal previous13
tainted = previous13
previous13 = number == 13
return True if tainted else previous13
total = 0
for tainted, subset in groupby(numbers, is_tainted):
if not tainted:
total += sum(subset)
return total
Upvotes: 0
Reputation: 972
This will solve your problem:
def sum13(nums):
"""jdhdjkls"""
if len(nums) == 0:
return 0
for i in range(0, len(nums)):
if nums[i] == 13:
nums[i] = 0
# problem arises when there are 2 consecutive 13 this if statement will rectify it.
if (i+1 < len(nums)) and (nums[i+1]!=13):
nums[i+1] = 0
return sum(nums)
Upvotes: 0
Reputation: 27577
You can use the built-in zip()
method to zip two lists skewed like:
[1, 2, 3, 4]
[1, 2, 3, 4]
to
[1, 2, 3, 4]
[2, 3, 4, None]
and check to see if any of the pairs have 13
in them.
Here is how:
def sum13(nums):
s = 0 if nums[0] == 13 else nums[0]
for p in zip(nums, nums[1:]):
if all(n != 13 for n in p):
s += p[1]
return s
print(sum13([1, 2, 2, 1, 13]))
print(sum13([13, 2, 2, 1]))
print(sum13([13, 13, 2, 13, 1, 5, 6, 13]))
Output:
6
3
11
You can also unpack the pairs:
def sum13(nums):
s = 0 if nums[0] == 13 else nums[0]
for i, j in zip(nums, nums[1:]):
if i != 13 != j:
s += j
return s
print(sum13([1, 2, 2, 1, 13]))
print(sum13([13, 2, 2, 1]))
print(sum13([13, 13, 2, 13, 1, 5, 6, 13]))
Upvotes: 1