High School Computer Science · Grades 10–12
22Recursion
A folder holds files and other folders, which hold files and other folders, as deep as anyone likes. How many files does it hold in all? A loop does not know how deep to go. But the question has a short answer in terms of itself: the files of a folder are its own files, plus the files of each folder inside it. A function that follows that sentence calls itself, and counts every file of the tree.
Such functions are called recursive. This chapter writes them, watches the machine run them, proves them correct, turns some of them back into loops, and ends on a famous puzzle whose recursive solution takes three lines and whose cost runs to hundreds of billions of years.
You already know
A function has parameters, local names and a returned value (the first book of the series). A loop is proved correct with an invariant and stops by a variant (chapter 16). A proof by induction shows a property for , then for whenever it holds for (the mathematics book, grade 12). Folders and paths (chapter 14).
22.1 A function that calls itself
Definition 22.1 (Recursive function, recursion)
A recursive function is a function whose body calls the function itself. Recursion is the method of solving a problem by reducing it to smaller instances of the same problem.
Definition 22.2 (Base case, recursive case)
The base case of a recursive function is an input for which it answers without calling itself. The recursive case is the part of the body that calls the function on smaller inputs and builds the answer from theirs.
The factorial , with , satisfies : the definition is already recursive. So are the sum of a list, its first element plus the sum of the rest, and the power .
def factorial(n):
"""n! = 1 x 2 x ... x n, for a whole number n >= 0."""
if n == 0: # base case
return 1
return n * factorial(n - 1) # recursive case
def sum_list(t):
"""The sum of the numbers of the list t."""
if t == []:
return 0
return t[0] + sum_list(t[1:])
def power(x, n):
"""x to the power n, for a whole number n >= 0."""
if n == 0:
return 1
return x * power(x, n - 1)
if __name__ == "__main__":
print([factorial(n) for n in range(8)])
print(factorial(25))
print(sum_list([3, 1, 4, 1, 5]), power(2, 10))
$ python factorial.py
[1, 1, 2, 6, 24, 120, 720, 5040]
15511210043330985984000000
14 1024
To see what happens, the next version prints each call and each return, indented by its depth.
def factorial(n, depth=0):
print(" " * depth + f"factorial({n}) called")
if n == 0:
result = 1
else:
result = n * factorial(n - 1, depth + 1)
print(" " * depth + f"factorial({n}) returns {result}")
return result
factorial(4)
$ python trace_calls.py
factorial(4) called
factorial(3) called
factorial(2) called
factorial(1) called
factorial(0) called
factorial(0) returns 1
factorial(1) returns 1
factorial(2) returns 2
factorial(3) returns 6
factorial(4) returns 24
22.2 The call stack
Definition 22.3 (Call stack, frame)
Each call of a function gets a frame: a region of memory holding its arguments, its local names and the place to return to. The frames of the calls not yet finished form the call stack: a call pushes a frame on top, and a return pops it.
Every call of factorial has its own n: the five n of the trace exist at the same time, one per frame, and do not overwrite one another. This is the stack of the toy machine’s CALL and RET (chapter 13), kept by Python for every call.
factorial(4) at its deepest point: six frames, the base case on top. Each frame keeps its own n until the call above it returns.The stack has a limit. A function that never reaches a base case, or reaches it too deep, fills the stack; Python stops it with RecursionError before the memory is exhausted.
import sys
def countdown(n):
if n == 0:
return "done"
return countdown(n - 1)
print("recursion limit:", sys.getrecursionlimit())
print(countdown(500))
sys.setrecursionlimit(100) # lowered, to fail quickly
try:
countdown(500)
except RecursionError as error:
print("RecursionError:", error)
$ python depth_error.py
recursion limit: 1000
done
RecursionError: maximum recursion depth exceeded
The function sys.getrecursionlimit gives the maximum depth of Python’s stack, and the function sys.setrecursionlimit changes it; the documentation warns that too high a limit can crash the interpreter, since the limit is there to protect the machine’s own stack.
22.3 Proving a recursive function
A recursive function is proved correct by induction on the size of its input: the base case is checked directly, and the recursive case is correct if the calls it makes, on smaller inputs, are.
Method 22.4 (Proving a recursive function)
- Correctness. State the property : “
f(n)returns the right value”. Check on the base cases. Assume for the smaller inputs the recursive case calls, and deduce it for . - Termination. Find a variant: a whole number, computed from the arguments, that is at least and strictly smaller at each recursive call. The calls then cannot go on forever.
For factorial: is “factorial(n) returns ”. holds, since it returns . If holds, then factorial(n) returns . By induction, holds for every . The variant is itself: a whole number, decreased by at each call, which reaches the base case . For a negative there is no variant, and indeed factorial(-1) never stops calling itself.
22.4 Recursion and loops
When the recursive call is the last thing done with a simple result, the function can be rewritten as a loop that performs the same operations in order. The loop needs no stack, and reaches sizes the recursion cannot.
from factorial import factorial, sum_list
def factorial_loop(n):
result = 1
for k in range(1, n + 1): # the multiplications the recursion does, in order
result *= k
return result
def sum_loop(t):
total = 0
for x in t:
total += x
return total
print(all(factorial(n) == factorial_loop(n) for n in range(100)))
print(sum_list(list(range(500))) == sum_loop(range(500)))
print(factorial_loop(3000) > 10**9000, "| factorial(3000) by recursion:", end=" ")
try:
factorial(3000)
except RecursionError:
print("RecursionError")
$ python loop_version.py
True
True
True | factorial(3000) by recursion: RecursionError
Recursion is the natural form when the data are themselves recursive: a folder of folders, a list of lists. The loop version would have to manage its own stack of what remains to visit.
"""Count the files under a folder, at any depth, on a tree built for the test."""
import tempfile
from pathlib import Path
def count_files(folder):
total = 0
for entry in folder.iterdir():
if entry.is_dir():
total += count_files(entry) # a folder: count what it holds
else:
total += 1 # a file: count it
return total
TREE = ["school/notes.txt", "school/maths/ch1.txt", "school/maths/ch2.txt",
"school/maths/old/ch0.txt", "photos/sea.jpg", "photos/2026/june/a.jpg",
"photos/2026/june/b.jpg", "photos/2026/july/c.jpg", "todo.txt"]
with tempfile.TemporaryDirectory() as top:
root = Path(top)
for name in TREE:
(root / name).parent.mkdir(parents=True, exist_ok=True)
(root / name).write_text("")
print("files:", count_files(root))
print("in photos:", count_files(root / "photos"))
print("in school/maths:", count_files(root / "school" / "maths"))
$ python count_files.py
files: 9
in photos: 4
in school/maths: 3
photos, two levels down for some.def nested_sum(item):
"""The sum of all numbers in item: a number, or a list of items."""
if not isinstance(item, list):
return item
return sum(nested_sum(x) for x in item)
marks = [12, [15, 9], [[8, 11], 14], [], [[[20]]]]
print(nested_sum(marks))
print(nested_sum(7), nested_sum([]))
$ python nested_sum.py
89
7 0
22.5 Three classics
The towers of Hanoi
Three pegs, A, B and C; on A, disks of decreasing sizes. The disks must all go to C, moving one disk at a time, never putting a disk on a smaller one. The recursive solution follows from looking at the largest disk: to move it, the others must be out of the way, on B.
def hanoi(n, start, goal, spare, moves):
"""Append to moves the moves taking n disks from start to goal."""
if n == 0:
return
hanoi(n - 1, start, spare, goal, moves) # the n - 1 smaller ones out of the way
moves.append((n, start, goal)) # the largest disk
hanoi(n - 1, spare, goal, start, moves) # the n - 1 smaller ones back on top
if __name__ == "__main__":
moves = []
hanoi(3, "A", "C", "B", moves)
for disk, a, b in moves:
print(f"disk {disk}: {a} -> {b}")
for n in [1, 2, 3, 4, 5, 10, 15, 20]:
moves = []
hanoi(n, "A", "C", "B", moves)
print(f"n = {n:2}: {len(moves):7} moves, 2**n - 1 = {2**n - 1}")
$ python hanoi.py
disk 1: A -> C
disk 2: A -> B
disk 1: C -> B
disk 3: A -> C
disk 1: B -> A
disk 2: B -> C
disk 1: A -> C
n = 1: 1 moves, 2**n - 1 = 1
n = 2: 3 moves, 2**n - 1 = 3
n = 3: 7 moves, 2**n - 1 = 7
n = 4: 15 moves, 2**n - 1 = 15
n = 5: 31 moves, 2**n - 1 = 31
n = 10: 1023 moves, 2**n - 1 = 1023
n = 15: 32767 moves, 2**n - 1 = 32767
n = 20: 1048575 moves, 2**n - 1 = 1048575
History — A puzzle sold with a legend
The puzzle was published in Paris in by the mathematician Édouard Lucas, under the name “N. Claus de Siam”, an anagram of “Lucas d’Amiens”. It came with a legend: at the creation, gold disks had been placed on one needle, priests were moving them by the puzzle’s rules, and when they finished the universe would end.
Drawings that contain themselves
The Koch curve replaces a segment by four segments a third as long, the middle two forming a peak, and does the same to each of them, and so on. A recursive function computes the points; depth is the segment itself.
"""Points of the Koch curve: each segment is replaced by four, recursively."""
import math
def koch(p, q, depth, points):
"""Append to points the curve from p to q, without q itself."""
if depth == 0:
points.append(p)
return
(x1, y1), (x2, y2) = p, q
dx, dy = (x2 - x1) / 3, (y2 - y1) / 3
a, b = (x1 + dx, y1 + dy), (x1 + 2 * dx, y1 + 2 * dy)
c, s = math.cos(math.pi / 3), math.sin(math.pi / 3)
peak = (a[0] + dx * c - dy * s, a[1] + dx * s + dy * c) # turned by 60 degrees
for u, v in [(p, a), (a, peak), (peak, b), (b, q)]:
koch(u, v, depth - 1, points)
def curve(depth):
points = []
koch((0.0, 0.0), (1.0, 0.0), depth, points)
return points + [(1.0, 0.0)]
figures/koch_points.py: segments, points.The naive Fibonacci numbers
The Fibonacci numbers start and continue by adding the two before. Written recursively as the definition says, the function is short and extremely slow.
calls = 0
def fib(n):
"""fib(0) = 0, fib(1) = 1, then each is the sum of the two before."""
global calls
calls += 1
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
for n in [5, 10, 15, 20, 25]:
calls = 0
value = fib(n)
print(f"fib({n:2}) = {value:6} calls: {calls:7}")
$ python fib_calls.py
fib( 5) = 5 calls: 15
fib(10) = 55 calls: 177
fib(15) = 610 calls: 1973
fib(20) = 6765 calls: 21891
fib(25) = 75025 calls: 242785
fib(5). The shaded calls repeat work already done elsewhere in the tree: the whole right subtree fib(3), and a second fib(2). The chapter on dynamic programming removes the repetition.22.6 Exercises
Exercise 22.1 ★
Write what trace_calls.py would print for factorial(3).
Solution
Solution of Exercise 22.1.
factorial(3) called
factorial(2) called
factorial(1) called
factorial(0) called
factorial(0) returns 1
factorial(1) returns 1
factorial(2) returns 2
factorial(3) returns 6
Exercise 22.2 ★
How many moves does hanoi make for disks? Which disk moves at the th move?
Solution
Solution of Exercise 22.2.
moves. The first move the four smaller disks to B; the th moves disk , the largest, from A to C; the last bring the four back on top of it.
Exercise 22.3 ★
What does reverse("loop") return, with reverse(s) returning "" for the empty string and otherwise reverse(s[1:]) + s[0]?
Solution
Solution of Exercise 22.3.
reverse("loop") is reverse("oop") + "l", which is reverse("op") + "o" + "l", and so on: "p" + "o" + "o" + "l", that is "pool".
Exercise 22.4 ★
How many frames of sum_list are on the stack at the deepest point of sum_list([4, 8, 15, 16, 23, 42])?
Exercise 22.5 ★
Write a recursive count_digits(n), the number of decimal digits of a whole number .
Solution
Solution of Exercise 22.5.
def count_digits(n):
if n < 10:
return 1
return 1 + count_digits(n // 10)
n // 10 drops the last digit. count_digits(2026) returns ; count_digits(0) returns , since is written with one digit.
Exercise 22.6 ★★
A student writes def total(n): return n + total(n - 1) for . What happens on total(3)? Correct it.
Solution
Solution of Exercise 22.6.
There is no base case: total(3) calls total(2), total(1), total(0), total(-1), and so on, until Python stops it with RecursionError. Correction: if n == 0: return 0 before the recursive case.
Exercise 22.7 ★★
What does factorial(-1) do? Change the function so that it refuses a negative number at once, with a clear error.
Solution
Solution of Exercise 22.7.
It calls factorial(-2), factorial(-3), …: the base case is never reached, and the run ends with RecursionError, a message that does not name the real mistake. Correction, at the top of the function:
if n < 0:
raise ValueError("factorial of a negative number")
Exercise 22.8 ★★
Write flatten(nested), which returns the numbers of a list of lists, at any depth, in order, in one flat list.
Solution
Solution of Exercise 22.8.
def flatten(nested):
if not isinstance(nested, list):
return [nested]
out = []
for item in nested:
out += flatten(item)
return out
flatten([1, [2, [3, 4]], [], 5]) returns [1, 2, 3, 4, 5].
Exercise 22.9 ★★
Prove by induction that power(x, n) returns for every whole number , and that it stops.
Solution
Solution of Exercise 22.9.
Let be “power(x, n) returns ”. : the function returns . If holds, then power(x, n) returns , so holds. By induction, holds for every . It stops: the variant is a whole number at least , decreased by at each call, so after calls it is , the base case.
Exercise 22.10 ★★
show(n) does nothing for , and otherwise calls show(n - 1), prints n, and calls show(n - 1) again. What does show(3) print? How many numbers does show(n) print?
Solution
Solution of Exercise 22.10.
1 2 1 3 1 2 1, one per line. show(n) prints numbers, with : the same relation as the towers of Hanoi, so . (It prints exactly the disks moved by hanoi, in order.)
Exercise 22.11 ★★
Write a recursive is_palindrome(s): a string of length at most is a palindrome; a longer one is, when its first and last characters are equal and the string between them is one.
Solution
Solution of Exercise 22.11.
def is_palindrome(s):
if len(s) <= 1:
return True
return s[0] == s[-1] and is_palindrome(s[1:-1])
The variant is the length, decreased by at each call; it ends at or .
Exercise 22.12 ★★★
Prove by induction that every solution of the towers of Hanoi with disks makes at least moves. (Look at the first time the largest disk moves.)
Solution
Solution of Exercise 22.12.
Let : “every solution for disks makes at least moves”. : at least one move, . Assume and take a solution for disks. The first time the largest disk moves, from A to some peg, the other disks are all on the third peg: it cannot sit on any of them, and it leaves A only when nothing is on it. Getting them there from A is a solution for disks: at least moves, by . The largest disk moves at least once. After its last move, it lies on C and the others must come onto it from wherever they are, all on one peg again, since the largest disk could only have moved with all of them elsewhere: at least more moves. In all at least . By induction, holds for every .
Exercise 22.13 ★★★
Let be the number of calls made by fib(n), the first call included. Prove that , and check it on the output.
Solution
Solution of Exercise 22.13.
fib(0) and fib(1) make one call each: , and . For , fib(n) makes itself one call plus all the calls of fib(n - 1) and fib(n - 2): . If the formula holds for and : . By induction (on two previous values), it holds for all . Check: , ; , , as printed.
Exercise 22.14 ★★★
Write a recursive subsets(t), which returns the list of all subsets of the list t, each as a list. How many does it return for a list of elements? Prove it.
Solution
Solution of Exercise 22.14.
def subsets(t):
if t == []:
return [[]]
rest = subsets(t[1:])
return rest + [[t[0]] + s for s in rest]
The subsets of t are those without t[0], the subsets of the rest, and those with it. If the rest, of elements, has subsets, t has ; the empty list has . By induction, subsets for elements.
Exercise 22.15 ★★★
Write a recursive binary(n), the binary writing of a whole number as a string, and prove it correct by induction.
Solution
Solution of Exercise 22.15.
def binary(n):
if n < 2:
return str(n)
return binary(n // 2) + str(n % 2)
Proof, by induction on , assuming the result for every smaller number. For and , the writing is the digit itself. For , with and . Since , binary(q) is the binary writing of ; appending the digit multiplies the value by and adds : the result is , with no leading zero since . binary(37) returns 100101.
22.7 Problem: The Sixty-Four Disks
Problem 22.1
Weekend problem — how long would the priests of the legend need?
The legend of the puzzle speaks of disks. This problem finds how many moves they need, proves that no one can do better, and turns the number into time.
"""The legend's tower: 64 disks, one move per second."""
from hanoi import hanoi
for n in range(1, 11): # check the formula on small towers
moves = []
hanoi(n, "A", "C", "B", moves)
assert len(moves) == 2**n - 1
moves_64 = 2**64 - 1
year = 365.25 * 24 * 3600 # seconds in a year, on average
print(f"moves for 64 disks: {moves_64:,}")
print(f"seconds in a year: {year:,.0f}")
print(f"years at one move per second: {moves_64 / year:,.0f}")
print(f"about {moves_64 / year / 1e9:.0f} billion years")
$ python sixty_four.py
moves for 64 disks: 18,446,744,073,709,551,615
seconds in a year: 31,557,600
years at one move per second: 584,542,046,091
about 585 billion years
Part I — The recursive solution.
- In
hanoi, what is the base case? What are the two recursive calls, and on which pegs? - Why does the largest disk never lie on a smaller one in this solution?
- Write the moves for .
- How deep does the call stack go for disks? Can
hanoi(64, ...)overflow the stack? - Why can the program not list the moves for disks, although its stack is shallow?
Part II — Counting the moves.
- Let be the number of moves made by
hanoifor disks. Give , and in terms of . - Compute to from that relation, and compare with the output of
hanoi.py. - How many times does the smallest disk move, for disks?
- How many times does the largest disk move?
Part III — Proofs.
- Prove by induction that .
- Prove by induction that every solution makes at least moves.
- Conclude: the program’s solution uses the fewest moves possible.
- What does
sixty_four.pycheck before computing, and why is it not a proof? - Why can
2**64 - 1be computed exactly, when the toy machine’s numbers stop at ?
Part IV — The legend’s time.
- How many moves do disks need? Read the output.
- Where does the number of seconds in a year, , come from?
- At one move per second, how many years does the task take?
- A machine that makes a billion moves per second: how many years?
- At one move per second, how many disks could be moved in years, a long human life? Find the largest whose moves fit.
- State the result: the number of moves for disks, and the time at one move per second.
Solution
Solution of Problem 22.1.
1. The base case is : nothing to move. The calls: disks from start to spare (using goal as spare), then disks from spare to goal (using start).
2. When the largest disk moves, the others are on the spare peg, so its start and goal pegs are empty; every other move belongs to a smaller puzzle in which disks larger than those moved are all at the bottom of their pegs, and can carry any of them.
3. Disk : A B; disk : A C; disk : B C.
4. frames of hanoi, from down to : for disks, far below the limit of .
5. The stack is shallow, but the list of moves would hold entries, more than any memory can hold, and producing them would take the time of Part IV.
6. and .
7. , , , , : as printed.
8. times: the smallest disk moves at every other move, starting with the first.
9. Once.
10. . If , then .
11. Exercise 22.12.
12. It makes moves, and no solution makes fewer: it is optimal.
13. That the moves are for to , with an assert. Ten cases checked do not prove the formula for , or for any not tried; the induction does.
14. Python’s integers grow as needed (chapter 3); the toy machine’s registers hold one byte.
15. .
16. : a year of days and a quarter, the average over leap years.
17. About million years: billion, rounded.
18. A billion times fewer: about years.
19. years are seconds. fits, does not: disks.
20. The disks need moves, the fewest possible; at one move per second, about billion years.