Sum Of Nested List In Python
I try to sum a list of nested elements e.g, numbers=[1,3,5,6,[7,8]] should produce sum=30 I wrote the following code : def nested_sum(L): sum=0 for i in range(len(L)):
Solution 1:
You need to use isinstance
to check whether an element is a list or not. Also, you might want to iterate over the actual list, to make things simpler.
def nested_sum(L):
total = 0 # don't use `sum` as a variable name
for i in L:
if isinstance(i, list): # checks if `i` is a list
total += nested_sum(i)
else:
total += i
return total
Solution 2:
It is generally considered more pythonic to duck type, rather than explicit type checking. Something like this will take any iterable, not just lists:
def nested_sum(a) :
total = 0
for item in a :
try:
total += item
except TypeError:
total += nested_sum(item)
return total
Solution 3:
I would sum the flattened list:
def flatten(L):
'''Flattens nested lists or tuples with non-string items'''
for item in L:
try:
for i in flatten(item):
yield i
except TypeError:
yield item
>>> sum(flatten([1,3,5,6,[7,8]]))
30
Solution 4:
A quick recursion that uses a lambda 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)
Solution 5:
This code also works.
def add_all(t):
total = 0
for i in t:
if type(i) == list: # check whether i is list or not
total = total + add_all(i)
else:
total += i
return total
Post a Comment for "Sum Of Nested List In Python"