sum of nested list in Python -
i seek sum list of nested elements
e.g, numbers=[1,3,5,6,[7,8]], sum=30
i wrote next code
def nested_sum(l): sum=0 in range(len(l)): if (len(l[i])>1): sum=sum+nested_sum(l[i]) else: sum=sum+l[i] homecoming sum
the above code gives next error: object of type 'int' has no len() tried len([l[i]]), still not working
anyone can help? btw, python 3.3
you need utilize isinstance
check whether element list or not. also, might want iterate on actual list, create things simpler.
def nested_sum(l): total = 0 # don't utilize `sum` variable name in l: if isinstance(i, list): # checks if `i` list total += nested_sum(i) else: total += homecoming total
python list
No comments:
Post a Comment