2

for example I have a list with numbers like this:

a = [10,[20,30],40] 

or

b = [[10,20],30]

Now I have to add all the elements in the above lists. so that if add the first list then I should get the answer as follows: 10+20+30+40 = 100. and for the second one b as follows: 10+20+30 = 60. The solution is to be expressed as a function. I have tried this one but it can be used for only adding if there is no nested list.

def sum(t):
    total = 0
    for x in t:
        total = total+x
    return total

Now can anyone help me solve this kind of problem in python programming. Thank you in advance!!!!!

Mp0int
  • 18,172
  • 15
  • 83
  • 114
Anivarth
  • 619
  • 5
  • 19

4 Answers4

1

You can use reduce:

x = reduce(lambda prev,el: prev+([x for x in el] if type(el) is list else [el]), x, [])

And use its result to feed your loop.

def sum(t):
    t = reduce(lambda prev,el: prev+([x for x in el] if type(el) is list else [el]), t, [])
    total = 0
    for x in t:
        total = total+x
    return total
0

Seems like the best approach would be to iterate over the top-level list and check each element's type (using is_instance(type, item)). If it's an integer, add it to the total, otherwise if it's a list, iterate over that list.

Making your function recursive would make it most usable.


Edit: For anybody stumbling upon this question, here's an example.

def nested_sum(input_list):
    total = 0
    for element in input_list:
        if isinstance(element, int):
            total += element
        elif isinstance(element, list):
            total += nested_sum(element)
        else:
            raise TypeError

    return total

Usage:

my_list = [72, 5, [108, 99, [8, 5], 23], 44]
print nested_sum(my_list)
>>> 364
TeaPow
  • 687
  • 8
  • 17
0

You can recursively flatten into a single list:

def flatten(lst, out=None):
    if out is None:
        out = []
    for item in lst:
        if isinstance(item, list):
            flatten(item, out)
        else:
            out.append(item)
    return out

Now you can just use sum:

>>> sum(flatten([10, [20, 30], 40]))
100
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
0

You need to define a recursion to handle the nested lists:

rec = lambda x: sum(map(rec, x)) if isinstance(x, list) else x

rec, applied on a list, will return the sum (recursively), on a value, return the value.

result = rec(a)
njzk2
  • 38,969
  • 7
  • 69
  • 107