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

How to consolidate the function of local_sum (list of mixed numbers and sublists) in one loop?

Given a list containing numbers, and sublists. The goal of this function – local_sum() is to get all local sum (or range sum) with these conditions: 1) if it’s a sublist, get its sum and remain a list, if consecutive numbers just add up them.

One example prob. will make it easier to follow:

(somehow I just got stuck in a nicer Pythonic way…)

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

from itertools import groupby

A =   [3, 4, 2, [10, 22, 32, 14], 9, 8, 6, [22, 11]]
expected = [9, 23,  [111]   
ans = [9, [78], 23, [33]]   <----   what I'm able to get

# is there a way to get this expected result in one shot, instead of doing another processing? 

# my current working code:
def local_sum(L):
    '''add up the numbers which are not in sublist,
       and sum the sublist as a one unit, if there're more than one -
       try to consolidate it into ONE.
    '''
    ans = []
    
    for k, g in groupby(L, key=lambda x: isinstance(x, list)):
        
        if k:                         # the group is a list
                                      # the whole list :: sum(list(g))X
            ans.append([sum(*g)])     # g is _grouper instance
            
        else:
            
            ans.append(sum(list(g)))           # each single number
    
    return ans

>Solution :

With only one example, it seems you want to keep a running total of everything in a sublist:

from itertools import groupby

A = [3, 4, 2, [10, 22, 32, 14], 9, 8, 6, [22, 11]]

def local_sum(L):
    ans = []
    sub = 0
    for k, g in groupby(A, key=lambda x: isinstance(x, list)):
        if k:
            sub += sum(*g)
        else:
            ans.append(sum(list(g)))
    ans.append([sub])
    return ans

print(local_sum(A))

Output:

[9, 23, [111]]
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