Skip to content

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.

15 min read0/4 questions

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.

Python
def factorial(n: int) -> int: if n <= 1: # base case: small enough to answer directly return 1 return n * factorial(n - 1) # recursive case: shrink the problem print(factorial(4))print(factorial(10))
Output
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).

Quick check
What happens when you call countdown(3)?
def countdown(n):
  print(n)
  countdown(n - 1)
Need a nudge? A hint rules out a wrong answer.

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.

The call stack for factorial(3)
  1. factorial(1)base case: returns 1
  2. factorial(2)waiting on factorial(1), then 2 × 1 = 2
  3. factorial(3)waiting on factorial(2), then 3 × 2 = 6
  4. <module>your script, waiting for the answer

Your script calls factorial(3). A frame with n = 3 is pushed. It cannot finish yet: it needs factorial(2).

1/5

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).

Predict the outputPython

What does this print?

def show(n):
  if n == 0:
      return
  print("down", n)
  show(n - 1)
  print("up", n)

show(2)
Need a nudge? Hints walk you through it.

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.

Python
import sysprint(sys.getrecursionlimit()) def depth(n): return 0 if n == 0 else 1 + depth(n - 1) print(depth(500))try: depth(100_000)except RecursionError as err: print("RecursionError:", err)
Output
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 whenUse a loop when
The data is nested: trees, folders, JSONThe 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
Python
def total_size(folder): """Sum file sizes in a nested dict of folders and files.""" size = 0 for value in folder.values(): if isinstance(value, dict): size += total_size(value) # a sub-folder: same problem, smaller else: size += value return size project = { "README.md": 2, "src": {"main.py": 10, "utils": {"io.py": 4, "math.py": 6}}, "tests": {"test_main.py": 5},}print(total_size(project))
Output
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 it in order4 steps

Put the steps for writing a recursive function in a sensible order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

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:

Python
calls = 0 def fib(n): global calls calls += 1 if n < 2: return n return fib(n - 1) + fib(n - 2) print(fib(20), "took", calls, "calls")
Output
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.

Calls made by fib(4), in order
1: fib(4)4: fib(1)base5: fib(0)base3: fib(2)6: fib(1)base2: fib(3)8: fib(1)base9: fib(0)base7: fib(2)root

fib(4) needs fib(3) and fib(2). Each of those makes two more calls, and so on.

1/4

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).

Python
from functools import cache calls = 0 @cachedef fib(n): global calls calls += 1 if n < 2: return n return fib(n - 1) + fib(n - 2) print(fib(20), "took", calls, "calls")print(fib(90))
Output
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.

Predict the outputPython

What does this print?

def total(nums):
  if not nums:
      return 0
  return nums[0] + total(nums[1:])

print(total([4, 5, 6]))
Need a nudge? Hints walk you through it.
ChallengeMedium

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([[[]]])                 →  []
Python
def flatten(items: list) -> list: # A nested list is a smaller version of the same problem. pass
ChallengeMedium

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
Python
def fib(n: int) -> int: # Recursion is fine, as long as you never compute the same fib twice. pass
Key terms
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.cache does it for you.
overlapping subproblems
When a recursion solves the same smaller problem many times, the sign memoization will help.