Home > Enterprise >  Sum numbers in a list with sublists
Sum numbers in a list with sublists

Time:12-14

I need to do a function that receives a list which every element can be an integer or a sublist of integers, and it must return the sum of each one.

For example: [2,[6,[8,10],8],[4,6]] this list must return 44 as its sum

if possible without using "isistance"

def sum_in_list(list):    
    new_list = [sum(l) for l in list]
    return new_list

CodePudding user response:

This solution sums multi-dimensional lists recursively.

multi_dim_list = [2, [6, [8, 10], 8], [4, 6]]

def multi_dim_list_summer(mda: list) -> int:
    local_sum = 0
    for e in mda:
        if isinstance(e, list):
            local_sum  = multi_dim_list_summer(e)
        elif isinstance(e, (int, float)):
            local_sum  = e
        else:
            print(f"No idea how to sum {e} of type {type(e)}; skipping")
    return local_sum


print(multi_dim_list_summer(multi_dim_array))
>>> 44

print(multi_dim_list_summer([[[1, 2, 3], 4, 5], 6, [[8, 9], [12, 13]]]))
>>> 63

See Roman's answer for a much more concise and pythonic version of this.

CodePudding user response:

Here is my quick solution using recursion:

def sum_in_list(lst):
    new_list = [sum_in_list(l) if isinstance(l, (list, tuple, set)) else l for l in lst]
    return sum(new_list)

CodePudding user response:

Use short recursive function to consider inner lists with arbitrary depth:

def deep_sum(lst):
    # ensure recur action on encountering inner list  
    return sum(deep_sum(item) if isinstance(item, list) else item
               for item in lst)


lst = [2, [6, [8, 10], 8], [4, 6]]
print(deep_sum(lst))  # 44
  • Related