PythiloLesson 21 of 30 · progress kept in this browser

Recursion

A recursive function calls itself on a smaller piece of the problem. It needs a base case that it answers directly, and every other call must move closer to that base case.

def countdown(n):
    if n == 0:          # base case
        return ["go"]
    return [n] + countdown(n - 1)

print(countdown(3))  # [3, 2, 1, 'go']

Recursion suits data that is shaped like itself, such as lists that contain lists:

def count_items(data):
    total = 0
    for x in data:
        if isinstance(x, list):
            total += count_items(x)
        else:
            total += 1
    return total

print(count_items([1, [2, [3]], 4]))  # 4

isinstance(x, list) asks whether x is a list. Each inner list is handled by the same function, however deep it sits. Python stops runaway recursion after about 1000 nested calls with RecursionError, so for a long, flat sequence a loop is the better tool.

Your task

Write nested_sum(data) returning the sum of all numbers in a list whose items may be numbers or lists, nested to any depth. Write depth(data) returning how deeply lists nest: [] and [1, 2] have depth 1, [1, [2]] has depth 2.