Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def nested_sum(L):
- sum=0
- for i in range(len(L)):
- if (len(L[i])>1):
- sum=sum+nested_sum(L[i])
- else:
- sum=sum+L[i]
- return sum
- 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
- def nested_sum(a) :
- total = 0
- for item in a :
- try:
- total += item
- except TypeError:
- total += nested_sum(item)
- return total
- rec = lambda x: sum(map(rec, x)) if isinstance(x, list) else x
- result = rec(a)
- 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
- >>> sum( sum(x) if isinstance(x, list) else x for x in L )
- 30
- def nested_sum(L):
- return sum( nested_sum(x) if isinstance(x, list) else x for x in L )
- 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
- def islist(x):
- return isintance(x, list)
- def notlist(x):
- return not isinstance(x, list)
- def nested_sum(lst):
- return sum(filter(notlist, lst)) + map(nested_sum, filter(islist, lst))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement