Video lecture
Watch on YouTube(opens in a new tab)Sub topic 13
Describing Algorithms Recursively
This chapter assumes you can read simple Python functions and the pseudocode conventions used earlier. It also assumes you know the decreasing-measure argument for termination from the chapter "Does It Stop? Arguing Termination." So far, every description of Euclid's algorithm has used a loop that changes variables step by step. A recursive description takes a different approach. It defines the answer to a problem in terms of the answer to a smaller instance of the same problem.
The Shape of a Recursive Description
A recursive description has two parts:
- A base case is an input simple enough that you can state the answer directly, without any further work.
- A recursive case reduces the input to a smaller input of the same kind, solves that smaller input with the same description, and builds the answer from that result.
A third requirement is implicit, and it is the one people most often get wrong. Every recursive case must move the input closer to a base case. If it doesn't, the description goes in circles and never finishes.
Euclid's algorithm fits this shape well. Written as a mathematical definition:
- gcd(a, 0) = a
- gcd(a, b) = gcd(b, a mod b), when b > 0
The first line is the base case. The second line is the recursive case. It rests on a fact from number theory: a and b have exactly the same common divisors as b and a mod b, so the two pairs have the same greatest common divisor.
The Same Algorithm in Three Notations
In pseudocode, a recursive description is a function that calls itself:
function GCD(a, b)
// Precondition: a >= 0, b >= 0, not both zero
// Postcondition: returns gcd(a, b)
if b = 0 then
return a
else
return GCD(b, a mod b)
end if
end functionIn Python it reads almost the same:
def gcd_recursive(a, b):
if b == 0:
return a
return gcd_recursive(b, a % b)
print(gcd_recursive(48, 18)) # 6There is no while and no reassignment of a and b. Each call receives fresh parameters. The "loop" happens through repeated calls, each working on a smaller pair.
Tracing a Recursive Algorithm
A state table for a loop records how the variables change over time. In recursion, nothing gets overwritten. Each call has its own copy of a and b, and those copies wait on the call stack, the runtime's list of calls that have started but not yet returned. To trace recursion, list each call with its arguments, note which case applies, and then record the return values as the calls unwind.
| Call depth | Call | Case | Returns |
|---|---|---|---|
| 0 | gcd(48, 18) | recursive: calls gcd(18, 48 mod 18 = 12) | 6 |
| 1 | gcd(18, 12) | recursive: calls gcd(12, 18 mod 12 = 6) | 6 |
| 2 | gcd(12, 6) | recursive: calls gcd(6, 12 mod 6 = 0) | 6 |
| 3 | gcd(6, 0) | base: b is 0 | 6 |
The argument pairs (48, 18), (18, 12), (12, 6), (6, 0) are the same states the iterative version passes through. That is no accident, as a later section explains.
You can make a program print its own trace by passing the depth along as an extra parameter:
def gcd_traced(a, b, depth=0):
print(" " * depth + f"gcd({a}, {b})")
if b == 0:
print(" " * depth + f"-> {a} (base case)")
return a
result = gcd_traced(b, a % b, depth + 1)
print(" " * depth + f"-> {result}")
return result
gcd_traced(48, 18)The indentation shows the call stack growing as the calls go in and shrinking as they return.
Arguing Termination for Recursion
The termination argument from the earlier chapter carries over directly. You need a measure that is a non-negative integer, that strictly decreases on every recursive call, and whose small values lead to a base case.
For gcd_recursive, the measure is the second argument, b. In the recursive case b > 0, and the new second argument is a mod b, which satisfies 0 ≤ a mod b < b. So b strictly decreases. A non-negative integer cannot decrease forever, so eventually b reaches 0, and b = 0 is exactly the base case.
Note what the argument depends on. If the precondition is dropped and negative inputs are allowed, then in Python a % b takes the sign of b. For example, gcd_recursive(5, -3) calls gcd_recursive(-3, -1). The argument still happens to reach 0 here, but the measure is no longer a non-negative integer, so the proof no longer applies. A termination argument is only as good as the precondition it relies on.
Arguing Correctness by Induction
Recursion lends itself to a style of correctness argument that matches its structure. It is induction on the decreasing measure:
- Base case: show the base case returns the right answer. gcd(a, 0) = a, because every integer divides 0, so the largest common divisor of a and 0 is a itself.
- Recursive case: assume the recursive call returns the correct answer for its smaller input. This assumption is called the inductive hypothesis. Then show that the current call builds the correct answer from it. Here gcd(b, a mod b) = gcd(a, b) by the number-theory fact, so returning the recursive result is correct.
Because the measure decreases toward the base case, these two steps together cover every valid input. This plays the same role as a loop invariant. In both cases, a property that holds at each step and at the end gives you the postcondition.
When the Work Happens After the Call
In Euclid's algorithm, the recursive call is the last thing the function does, and its result passes up unchanged. This is called tail recursion. Many recursive descriptions still have work to do after the call returns. Here is the maximum of a list described recursively:
def find_max_recursive(xs):
# Precondition: xs is a non-empty list of comparable values
if len(xs) == 1:
return xs[0]
rest_max = find_max_recursive(xs[1:])
return xs[0] if xs[0] > rest_max else rest_max
print(find_max_recursive([3, 9, 2, 7])) # 9The definition reads: the maximum of a one-element list is that element. The maximum of a longer list is the larger of its first element and the maximum of the rest. The measure is len(xs), which drops by 1 on each call and stops at 1. Each call has to wait for its sub-result before it can do the comparison, so the trace has real work on the way back up:
| Call | Waits for | Then compares | Returns |
|---|---|---|---|
| max([3, 9, 2, 7]) | max([9, 2, 7]) = 9 | 3 vs 9 | 9 |
| max([9, 2, 7]) | max([2, 7]) = 7 | 9 vs 7 | 9 |
| max([2, 7]) | max([7]) = 7 | 2 vs 7 | 7 |
| max([7]) | nothing (base case) | none | 7 |
Recursive Versus Iterative Descriptions
A tail-recursive description converts mechanically into a loop. The parameters of the next call become assignments, and the base-case test becomes the loop's exit condition. Applied to gcd_recursive, this conversion produces exactly while b != 0: a, b = b, a % b. That is why the two versions pass through identical states.
| Concern | Recursive description | Iterative description |
|---|---|---|
| Closeness to a mathematical definition | Often a direct match | Needs translation into state updates |
| Correctness argument | Induction on the measure | Loop invariant |
| Termination argument | Measure decreases on each call | Measure decreases on each iteration |
| Memory | One stack frame per pending call | Fixed set of variables |
| Practical limit in Python | Default depth limit of about 1000 calls | None from depth |
The depth limit matters when you turn a description into a program. Euclid's algorithm needs very few calls even for huge numbers, because the number of steps grows only with the number of digits. find_max_recursive makes one call per element, so a list of 5,000 items raises RecursionError. It also copies the list at every call with xs[1:]. A recursive description can be the clearest way to explain an algorithm and still be the wrong way to implement it.
import sys
print(sys.getrecursionlimit()) # usually 1000 in CPythonCommon Errors
| Error | Symptom | Fix |
|---|---|---|
| Missing base case | Infinite recursion, `RecursionError` | Handle the simplest input directly |
| Recursive call doesn't shrink the input | Infinite recursion | Identify the measure and check that it strictly decreases |
| Base case unreachable for some inputs | Works on tests, fails on edge cases | Check the base case against the precondition, e.g. an empty list for `find_max_recursive` |
| Result of the recursive call ignored | Wrong answer or `None` | Return or use the recursive result |
| Too many base cases | Redundant, inconsistent code | Keep only the base cases the measure actually reaches |
Exercise
Write a recursive description of sum_list(xs), which returns the sum of a list of numbers (an empty list sums to 0). Identify the base case, the recursive case, and the decreasing measure, and say whether it is tail-recursive.
Show answer
Base case: if xs is empty, return 0. Recursive case: return xs[0] + sum_list(xs[1:]). The measure is len(xs), a non-negative integer that drops by 1 on each call and reaches 0, the base case. It is not tail-recursive, because the addition happens after the recursive call returns.
Exercise
Trace gcd_recursive(35, 21). List every call, the case that applies, and the value each call returns.
Show answer
gcd(35, 21) is recursive and calls gcd(21, 14). gcd(21, 14) calls gcd(14, 7). gcd(14, 7) calls gcd(7, 0). gcd(7, 0) is the base case and returns 7. Every call returns 7.
Exercise
A student writes def f(n): return 1 if n == 0 else n * f(n - 2), intending to compute a product of numbers. For which non-negative integers n does it terminate, and why?
Show answer
It terminates only for even n. The measure n decreases by 2 on each call, so even values reach 0, the base case. Odd values skip from 1 to -1 and keep decreasing forever, so the base case is never reached. Either restrict the precondition to even n or add a base case for n == 1.