Lesson 15 of 52Functions
Recursion
Write functions that call themselves with a base case, picture the call stack, and speed them up with functools.cache.
Some problems are made of smaller copies of themselves: a folder contains folders, a comment thread contains replies, a JSON object contains objects. Recursion, a function calling itself, is the natural way to handle them. It is also the foundation for the tree, graph and backtracking problems that fill the later interview units, so it is worth getting comfortable with now.
A function that calls itself
The factorial of n, written n!, is n × (n - 1) × ... × 1. So 4! = 4 × 3 × 2 × 1 = 24. Notice that 4! is just 4 × 3!. The problem contains a smaller version of itself. That is the shape recursion fits.
Press Run (⌘ Enter) to see what happens.Every recursive function needs two parts:
- A base case: an input simple enough to answer without recursing. Here,
n <= 1. - A recursive case: a call on a smaller input that moves toward the base case. Here,
n - 1.
Forget the base case, or fail to shrink the input, and the function calls itself forever (until Python stops it).
countdown(3)?def countdown(n): print(n) countdown(n - 1)
The call stack
How does Python keep track of all those unfinished calls? Each call gets a frame: a small record holding its local variables and where to resume. Frames are kept on the call stack. A new call is pushed on top; when a call returns, its frame is popped off and the one below continues.
Your script calls factorial(3). A frame with n = 3 is pushed. It cannot finish yet: it needs factorial(2).
The key insight: each call has its own n. The calls do not overwrite each other, they wait in line. Work happens on the way down (making calls) and on the way back up (combining results).
What does this print?
def show(n):
if n == 0:
return
print("down", n)
show(n - 1)
print("up", n)
show(2)The recursion limit
The stack is not infinite. CPython limits recursion depth to about 1000 frames by default, to avoid crashing the interpreter. Hitting it raises RecursionError.
Press Run (⌘ Enter) to see what happens.You can raise the limit with sys.setrecursionlimit, but that is usually the wrong fix. Unlike some languages, Python does not do tail-call optimisation, so even "tail recursive" functions use one frame per call. If your input can be thousands of levels deep, use a loop.
Recursion vs loops
Anything you can write recursively you can write with a loop (and a stack, if needed), and vice versa. Choose by clarity:
| Use recursion when | Use a loop when |
|---|---|
| The data is nested: trees, folders, JSON | The data is flat: a list, a range |
| The problem splits into smaller copies (divide and conquer) | You just repeat a step until done |
| Depth is small (hundreds, not millions) | Depth could be very large |
Press Run (⌘ Enter) to see what happens.A loop version of total_size is possible but clumsier. Recursion matches the shape of the data.
Put the steps for writing a recursive function in a sensible order.
- Tap the steps below in the right order.
Repeated work, and memoization
The Fibonacci numbers are 0, 1, 1, 2, 3, 5, 8, ..., where each is the sum of the two before. The recursive definition is beautiful and very slow:
Press Run (⌘ Enter) to see what happens.Draw the calls for fib(4) and you can see why. The same subproblems are solved again and again.
fib(4) needs fib(3) and fib(2). Each of those makes two more calls, and so on.
The fix is memoization: remember each answer the first time you compute it, and reuse it after that. Python has it built in. Put @functools.cache above the function (the @ line is a decorator, which wraps a function; you will learn how they work later).
Press Run (⌘ Enter) to see what happens.Each fib(k) is now computed once, so fib(n) takes about n calls instead of about 2ⁿ. That is the core idea of dynamic programming, which has a whole unit in the Algorithms & Patterns course.
What does this print?
def total(nums):
if not nums:
return 0
return nums[0] + total(nums[1:])
print(total([4, 5, 6]))Flatten any depth
Write flatten(items) that takes a list that may contain lists, which may contain lists, and so on, and returns one flat list of all the non-list values in order.
flatten([1, [2, [3, [4]]], 5]) → [1, 2, 3, 4, 5]
flatten([[[]]]) → []Fast Fibonacci
The Fibonacci numbers start 0, 1 and each next one is the sum of the two before: 0, 1, 1, 2, 3, 5, 8, …. Write fib(n) that returns the nth one (fib(0) == 0, fib(1) == 1).
It must be fast for n up to 70. The plain recursive version makes billions of calls for fib(40).
fib(10) → 55
fib(70) → 190392490709135- recursion
- A function solving a problem by calling itself on a smaller version of it.
- base case
- An input simple enough to answer without recursing. Without one, recursion never stops.
- call stack
- The stack of frames for calls in progress. Each call has its own local variables.
- RecursionError
- Raised when calls nest deeper than the limit (about 1000 by default in CPython).
- memoization
- Caching results of calls so each input is computed only once.
@functools.cachedoes it for you. - overlapping subproblems
- When a recursion solves the same smaller problem many times, the sign memoization will help.