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

Iterating through list with count resetting on 0

So I am working on algorithms and I have this section where I can’t figure out.
Given a list of numbers, get the sum of consecutive values over 0 and add to new list.
Expected result:

[1, 2, 3, 0, 1, 1, 1, 0, 2, 2, 2] == [6, 3, 6]

I have tried:

    for i in splitlist2:   
    if i == 0:
        resultlist.append((count2))
        count2 = 0
    else:
        count2 += i

Produces [6, 3]. I don’t get why the last value is not appearing. Can someone please explain?

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

>Solution :

def custom_sum(arr): 
    if not arr: return [] 
    res = [0] 
    for i, el in enumerate(arr): 
        if el == 0: 
            if i != len(arr)-1: 
                res.append(0) 
        else:
            res[-1] += el 
    return res

A quick test:

arr = [1, 2, 3, 0, 1, 1, 1, 0, 2, 2, 2]
custom_sum(arr)
[6, 3, 6]

The general algorithm:

  1. If the input array is empty return empty array
  2. Otherwise initialize a result array with a 0
  3. Loop over the elements of the input array:
  4. If the element is 0, check whether it’s the last element. If it’s the last element of the input array, ignore. Otherwise, add a zero to the result array for a new partition.
  5. If the element is not zero, add its value to the last value in result array.
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