Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Set list elements to 0 from an index to the end if partial sum is under certain value

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading