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.
Asked
Active
Viewed 69 times
0

Srikar Appalaraju
- 71,928
- 54
- 216
- 264

Arian Disd
- 1
- 1
-
1another homework assignment. Can't get any more blatant than this – iruvar Jul 12 '13 at 05:19
1 Answers
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
- 244,495
- 58
- 464
- 504
-
-
I think `if isinstance(x, Iterable) and not isinstance(x, str)` is more general though here there is only int. – zhangyangyu Jul 12 '13 at 05:38
-
@zhangyangyu If list contains non-numeric values then `sum()` will raise an error too, so no need to handle strings here. – Ashwini Chaudhary Jul 12 '13 at 05:41
-