Sub topic 4
Why It Works: Induction and Recursive Correctness
This chapter assumes you can read Python functions, know the recursive factorial from the previous chapter, and have seen proof by mathematical induction at least once, even informally. You do not need any formal logic. The goal is a practical habit: when you write a recursive function, you should be able to say in a few sentences why it returns the right answer and why it stops.
Tracing the call stack shows what a recursive function does for one input. Induction shows what it does for every input. Tracing factorial(5) by hand is useful, but it tells you nothing about factorial(5000). An induction argument covers all of them at once.
The Principle of Induction
Mathematical induction proves that a statement P(n) holds for every integer n ≥ 0. It has two parts:
- Base case. Show P(0) is true.
- Inductive step. Show that if P(k) is true for some k ≥ 0, then P(k + 1) is also true.
Once both parts hold, every number is covered. P(0) holds by the base case. P(1) follows from P(0) by the step, P(2) follows from P(1), and so on with no gaps.
A recursive function has the same two parts. Its base case handles the smallest inputs directly. Its recursive case handles a larger input by assuming a smaller call already works. The proof's structure matches the code's structure, which is why induction suits recursion so well.
Proving Factorial Correct
Here is the function again:
def factorial(n):
if n < 0:
raise ValueError("n must be non-negative")
if n == 0:
return 1
return n * factorial(n - 1)
print(factorial(5)) # 120Claim. For every integer n ≥ 0, factorial(n) returns n!.
Base case (n = 0). The guard n < 0 is false, and n == 0 is true, so the function returns 1. By definition 0! = 1, so P(0) holds.
Inductive step. Assume factorial(k) returns k! for some k ≥ 0. This assumption is the inductive hypothesis. Now consider factorial(k + 1). Since k + 1 ≥ 1, neither guard fires, and the function returns (k + 1) * factorial(k). By the hypothesis, factorial(k) returns k!, so the result is (k + 1) · k! = (k + 1)!. P(k + 1) holds.
Both parts hold, so factorial is correct for every non-negative integer.
The inductive step never traces the recursion past one level. You assume the recursive call is correct and check only the work done in the current frame. Programmers call this the "recursive leap of faith." Induction is the reason the leap is safe.
The Second Obligation: Termination
The proof above quietly assumed that factorial(k) returns at all. A complete correctness argument has two halves:
| Property | Question it answers | How to show it |
|---|---|---|
| Partial correctness | If the function returns, is the answer right? | Induction on the input |
| Termination | Does the function always return? | A measure that strictly decreases and cannot decrease forever |
A measure is a non-negative integer computed from the arguments that gets strictly smaller with every recursive call. For factorial, the measure is n itself: each call goes from n to n − 1, and n cannot drop below 0 without hitting the base case. Because non-negative integers cannot decrease forever, the recursion must reach the base case.
Induction on n proves both halves together for factorial, because the induction itself walks down the same chain of values the calls do. They come apart when the recursive call does not reach the base case. Here is a broken variant:
def bad_factorial(n):
if n == 0:
return 1
return n * bad_factorial(n - 2)
print(bad_factorial(4)) # 8, which is wrong but terminates
try:
bad_factorial(3)
except RecursionError:
print("bad_factorial(3) never reached its base case")For odd n the argument goes 3, 1, −1, −3, and never equals 0. The measure n does decrease, but it is no longer bounded below by the base case, so the recursion runs until Python's depth limit stops it. Even inputs terminate but compute the wrong value, which an inductive step would catch at once: n · (n − 2)! is not n!.
Strong Induction for Multiple Recursive Calls
Ordinary induction lets you assume only P(k) when proving P(k + 1). Many recursive functions call themselves on inputs that are smaller by more than one. Strong induction handles this. In the inductive step you may assume P(j) for every j smaller than n, not just n − 1.
Fibonacci, which a later chapter studies in detail, needs this:
def fib(n):
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
print(fib(10)) # 55Claim. For every n ≥ 0, fib(n) returns F(n), where F(0) = 0, F(1) = 1, and F(n) = F(n − 1) + F(n − 2) for n ≥ 2.
Base cases. For n = 0 and n = 1, n < 2 is true and the function returns n, which matches F(0) = 0 and F(1) = 1. You need two base cases because the step reaches back two values. With only n = 0 as a base case, fib(1) would call fib(-1), which the definition does not cover.
Inductive step. Let n ≥ 2 and assume fib(j) returns F(j) for all 0 ≤ j < n. Both n − 1 and n − 2 are in that range, so the function returns F(n − 1) + F(n − 2) = F(n).
This proof says nothing about speed. fib is correct and also takes exponential time. Correctness and efficiency are separate questions, and later chapters handle the second one.
Halving Recursion: Exponentiation by Squaring
Strong induction is especially useful for divide-and-conquer functions, where the recursive input is roughly half the original. You will meet this function properly in a later chapter. Here we only check that it is correct.
def fast_power(x, n):
if n == 0:
return 1
half = fast_power(x, n // 2)
if n % 2 == 0:
return half * half
return half * half * x
print(fast_power(3, 5)) # 243
print(fast_power(2, 10)) # 1024Claim. For every integer n ≥ 0, fast_power(x, n) returns xⁿ.
Base case. n = 0 returns 1 = x⁰.
Inductive step. Let n ≥ 1 and assume the claim for all smaller exponents. Since n ≥ 1, we have n // 2 < n, so the hypothesis gives half = x^(n // 2). Write q = n // 2.
- If n is even, n = 2q, and
half * half= x^q · x^q = x^(2q) = xⁿ. - If n is odd, n = 2q + 1, and
half * half * x= x^(2q) · x = xⁿ.
Termination comes from the same fact: n // 2 < n for every n ≥ 1, so the exponent strictly decreases and must reach 0.
The condition n ≥ 1 matters. For n = 0, n // 2 is also 0, which would recurse forever, and the base case is what prevents that. Python's // also rounds toward negative infinity, so (−1) // 2 is −1. A negative exponent would never reach 0. Handling negative exponents needs its own case, which a later chapter adds.
Strengthening the Claim for Accumulators
Sometimes the obvious claim cannot be proved directly. Consider a version that carries a partial product in an extra parameter:
def factorial_acc(n, acc=1):
if n == 0:
return acc
return factorial_acc(n - 1, acc * n)
print(factorial_acc(5)) # 120Try to prove "factorial_acc(n) returns n!" and the inductive step gets stuck. The recursive call is factorial_acc(n - 1, n), with an accumulator other than 1, and the hypothesis says nothing about that call.
The fix is to prove a stronger, more general claim that covers every accumulator value:
Claim. For every n ≥ 0 and every number a, factorial_acc(n, a) returns a · n!.
- Base case.
factorial_acc(0, a)returns a = a · 0!. - Inductive step. Assume the claim for k and all accumulators. Then
factorial_acc(k + 1, a)returnsfactorial_acc(k, a * (k + 1)), which by hypothesis equals a · (k + 1) · k! = a · (k + 1)!.
Setting a = 1 gives the original claim. A stronger statement makes a stronger hypothesis, and that is often what lets the step go through. The tail-recursion chapter uses this same invariant.
Testing Versus Proving
Tests and proofs do different jobs. A test checks finitely many inputs. A proof covers all of them, but only for the function you actually reasoned about. Typing mistakes in the code can still break a correct argument. Use both:
import math
def factorial(n):
if n < 0:
raise ValueError("n must be non-negative")
if n == 0:
return 1
return n * factorial(n - 1)
for n in range(0, 200):
assert factorial(n) == math.factorial(n), n
print("factorial matches math.factorial for 0..199")Common Mistakes in Recursive Correctness Arguments
| Mistake | Symptom | Fix |
|---|---|---|
| Missing a base case the step relies on | Calls with inputs outside the domain, such as `fib(-1)` | Add base cases for every value the step can reach that it cannot reduce |
| Assuming the hypothesis for a value that is not smaller | Circular proof and infinite recursion | Check that each recursive argument is strictly smaller by your measure |
| Measure decreases but skips the base case | `RecursionError` on some inputs | Use a range test or restrict the domain |
| Proving a claim too narrow for the recursive call | Inductive step cannot use the hypothesis | Generalize the claim, for example over all accumulator values |
| Confusing correctness with efficiency | "It's proven, so it's fine" for exponential code | Analyze running time separately |
Exercise
The function def sum_to(n): return 0 if n == 0 else n + sum_to(n - 1) is meant to return 0 + 1 + ... + n. Write the induction proof that it returns n(n + 1)/2 for all n ≥ 0, and state the measure that shows it terminates.
Show answer
Base case: sumto(0) returns 0 = 0·1/2. Inductive step: assume sumto(k) = k(k + 1)/2 for some k ≥ 0. Then sum_to(k + 1) returns (k + 1) + k(k + 1)/2 = (k + 1)(2 + k)/2 = (k + 1)(k + 2)/2, which is the formula for k + 1. Termination: the measure is n, a non-negative integer that drops by 1 each call and stops at the base case n == 0.
Exercise
Someone changes the base case of fast_power from if n == 0: return 1 to if n == 1: return x. Which inputs break, and which part of the correctness argument fails?
Show answer
Only n = 0 breaks. fastpower(x, 0) skips the base case and calls fastpower(x, 0 // 2) = fast_power(x, 0) again, so it recurses until RecursionError. Termination fails because n // 2 < n is false when n = 0, so the measure does not decrease. For n ≥ 1, halving eventually reaches 1, which the new base case handles correctly, so those inputs still work.
Exercise
Why does the proof that fib is correct need strong induction and two base cases, while the factorial proof needs neither?
Show answer
fib(n) calls fib(n - 2) as well as fib(n - 1), so the inductive step must assume correctness for two smaller values, not just the one before n. Strong induction allows assuming the claim for all j < n. Because the step reaches back two values, it only applies for n ≥ 2, so n = 0 and n = 1 must both be handled as base cases. Factorial reaches back one value, so ordinary induction with the single base case n = 0 is enough.