Reputation: 79
Given a Python list whose elements are either integers or lists of integers (only we don't know how deep the nesting goes), how can we find the sum of each individual integer within the list?
It's fairly straightforward to find the sum of a list whose nesting only goes one level deep, e.g.
[1, [1, 2, 3]]
# sum is 7
But what if the nesting goes two, three, or more levels deep?
[1, [1, [2, 3]]]
# two levels deep
[1, [1, [2, [3]]]]
# three levels deep
The sum in each of the above cases is the same (i.e. 7). I think the best approach is using recursion where the base case is a list with a single integer element, but beyond that I'm stuck.
Upvotes: 0
Views: 3915
Reputation: 11026
One approach: flatten the list, then use sum()
.
from collections import Iterable
def flatten(lst):
for i in lst:
if isinstance(i, Iterable) and not isinstance(i, basestring):
for sublst in flatten(i):
yield sublst
else:
yield i
sum(flatten([1, [1, [2, [3]]]]))
If you are dealing only with lists, change isinstance(i, Iterable)
to isinstance(i, list)
for a massive performance boost.
Note that the basestring
check is not necessary when using sum()
as Ashwini pointed out.
Upvotes: 2
Reputation: 6693
Assuming that you are only using lists, this should do the trick:
def sum_nested(l):
s = 0
for item in l:
if type(item) is list:
s += sum_nested(item)
else:
s += item
return s
Upvotes: 4
Reputation: 3500
Easiest way I can think of:
from compiler.ast import flatten
sum(flatten(numbs))
Upvotes: 5
Reputation: 250881
You can use this recursive solution:
from collections import Iterable
def flatten(collection):
for element in collection:
if isinstance(element, Iterable):
for x in flatten(element):
yield x
else:
yield element
Demo:
>>> lis = [1, [1, [2, [3]]]]
>>> sum(flatten(lis))
7
>>> lis = [1, [1, 2, 3]]
>>> sum(flatten(lis))
7
>>> lis = [1, [1, [2, 3]]]
>>> sum(flatten(lis))
7
Upvotes: 7