Recursionrecursion-deep-sum
LessonΒ·difficulty 3/5Β·~14 min
Recursion: deep sum
Recursion: deep sum
A recursive function calls itself on a smaller piece of the problem. Every recursion needs a base case that stops it:
python
def total(x):
if isinstance(x, list):
return sum(total(item) for item in x) # recurse into each item
return x # base case: a plain int
isinstance(x, list) asks "is this a list?". This lets one function handle a
value that might be a number or a nested list of numbers, at any depth.
Your task
Write deep_sum(x) where x is an int or a (possibly nested) list of
ints/lists. Return the sum of every int at any depth.
python
deep_sum([1, [2, [3, 4]], 5]) # 15
deep_sum([]) # 0
deep_sum(7) # 7
Hint: if isinstance(x, list), return the sum of deep_sum(item) for each
item; otherwise x is an int, so just return it.
Tests
- nested mix
- empty list
- bare int
- flat list
- deeply nested (hidden)
- negatives and empties (hidden)
Stuck? Ask for a spark
warming up
Loading editorβ¦
$ Console output will appear here.