Recursion: deep sum
A recursive function calls itself on a smaller piece of the problem. Every recursion needs a base case that stops it:
def countdown(n):
if n == 0:
return "liftoff" # base case: stop recursing
return countdown(n - 1) # recurse on a smaller n
For nested data, the base-vs-recurse test is usually a type check:
isinstance(x, list) asks "is this a list?". That lets one function handle a
value that might be a plain number or a nested list of numbers, at any depth β
recurse when there's more structure to dig into, stop when there isn't.
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.
deep_sum([1, [2, [3, 4]], 5]) # 15
deep_sum([]) # 0
deep_sum(7) # 7
Hint: two cases. When x is a list, the answer is the combined deep_sum of
each item inside it; otherwise x is a plain int that already stands for its
own total.
Tests
- nested mix
- empty list
- bare int
- flat list
β¦ Stuck? Ask for a spark
Sign in or create a free account to use your monthly AI explainer allowance.
$ Console output will appear here.