Having a list of numbers, say:
numbers = [4, 5, 7, 2]
How could I write a function f that takes the list and a value and returns these results (I think the examples explains better):
f(numbers, 4)
[4, 0, 0, 0]
f(numbers, 3)
[0, 0, 0, 0]
f(numbers, 10)
[4, 5, 0, 0]
f(numbers, 17)
[4, 7, 7, 0]
I need to update the list with zeros from and index i such that sum(l[0:i]) <= val and sum(l[0:i+1]) > val.
I tried:
def f(numbers, val, last_index=-1):
if sum(numbers[0:last_index]) > val:
numbers[last_index] = 0
last_index -= 1
f(numbers, val, last_index)
I need to mutate the objects contained in the list. Not allowed to make copies. The function I’ve written does not work.
>Solution :
I would use a loop with enumerate rather than recursion:
def f(nums,target):
total = 0
for i,n in enumerate(nums):
if total <= target: total += n
if total > target:
nums[i:] = [0]*(len(nums)-i)
break
passes all of your test cases (after the typo is removed from the last).