0

A function named add_r that takes a list as argument and adds all numeric values in all levels of the provided list. Assume that the input list will always be a list of numbers or sub-lists that may contain further sub-lists and/or numbers. For example, add_r( [[1, 2], [3], [[4, 5, 6], [7, 8, [9, 10]]]]) should return 55. Take into account that the input list provided as argument to the function can contain sublists at any depth.

Srikar Appalaraju
  • 69,116
  • 53
  • 210
  • 260

1 Answers1

2

Use a recursive function:

from collections import Iterable
def add_r(lis):
     for x in lis:
         if isinstance(x, Iterable):
             for y in add_r(x):
                 yield y
         else:        
             yield x

>>> lis = [[1, 2], [3], [[4, 5, 6], [7, 8, [9, 10]]]]
>>> sum(add_r(lis))
55

On py2.x you can also use compiler.ast.flatten:

>>> from compiler.ast import flatten
>>> sum(flatten(lis))
55
Ashwini Chaudhary
  • 232,417
  • 55
  • 437
  • 487