fork download
  1. def iterative_sum(lst):
  2. s = 0
  3. for i in lst:
  4. if isinstance(i, list):
  5. lst += i
  6. else:
  7. s += i
  8. return s
  9.  
  10. def recursive_sum(lst):
  11. if not isinstance(lst, list):
  12. return lst
  13. if lst:
  14. return recursive_sum(lst[0]) + recursive_sum(lst[1:])
  15. return 0
  16.  
  17. print(iterative_sum([1, 2, [3, 4], [5, [[6, 7], 8]], 9]))
  18. print(recursive_sum([1, 2, [3, 4], [5, [[6, 7], 8]], 9]))
Success #stdin #stdout 0.03s 9532KB
stdin
Standard input is empty
stdout
45
45