Chapters
Python114 chapters

Exercises

Recursion

3 tasks. Write the code, press Check, and the page runs it against a real Python interpreter.

Exercise 1

Write factorial recursively.

Python
def factorial(n):
    # base case, then the recursive step
    pass

print(factorial(5))
Exercise 2

Add up every number in the nested lists, however deep they go.

Python
def total(items):
    # recurse into any nested lists
    pass

print(total([1, [2, 3], [4, [5, 6]]]))
Exercise 3

This recomputes the same values enormously often. Cache it so fib(30) is instant.

Python
def fib(n):
    if n < 2:
        return n
    return fib(n - 1) + fib(n - 2)

print(fib(30))