1.2.38 · D3Introduction to Programming (Python)

Worked examples — Classic recursion — factorial, Fibonacci, binary search

2,904 words13 min readBack to topic

The scenario matrix

Every recursion problem lives somewhere in a small grid of situations. If a walkthrough never showed you a cell, you'd be guessing when you hit it. Here is the full grid we will cover — each cell names the tricky thing that could go wrong there.

# Machine Scenario class The tricky thing
A factorial typical n>0 the multiplications pile up, then unwind
B factorial boundary n=0 base case fires immediately, no recursion
C factorial invalid n<0 there is no base case below 0 → infinite recursion
D fibonacci boundary n=0, n=1 two base cases, why two
E fibonacci typical n≥2 naive the call tree branches and repeats work
F fibonacci same n memoized each subproblem computed once
G binary search target present halving converges onto the index
H binary search target absent the range collapses (lo>hi) → -1
I binary search target at an edge first or last element, off-by-one danger
J binary search unsorted input the "throw away a half" logic is invalid
K word problem real-world phone-book / dictionary lookup as binary search

The examples below are tagged with the cell(s) they hit. Together they touch A–K.


Example 1 — factorial, typical case n=4 (cell A)


Example 2 — factorial boundary n=0 (cell B)


Example 3 — factorial invalid n=-3 (cell C, degenerate)


Example 4 — Fibonacci base cases n=0, n=1 (cell D)


Example 5 — naive Fibonacci fib(5), the repeated work (cell E)


Example 6 — memoized Fibonacci fib(30) (cell F)


Example 7 — binary search, target present (cell G)


Example 8 — binary search, target absent (cell H, degenerate collapse)


Example 9 — binary search at the edges (cell I, off-by-one)


Example 10 — binary search on UNSORTED input (cell J, invalid precondition)


Example 11 — real-world word problem (cell K)


Recall Quick self-test on the matrix

factorial(-2) does what, and why? ::: Raises RecursionError — n-1 moves away from the base case 0, so it never terminates. Why does Fibonacci need two base cases but factorial needs one? ::: fib reaches back two steps (n-1 and n-2), so two known starting values are required or it recurses below 0. What does binary search return, and how does it detect, a missing target? ::: -1, detected when the range collapses to lo > hi (empty window). Binary search returned -1 for a value you know is present — likely cause? ::: The array wasn't sorted; the halving logic is invalid on unsorted data. Worst-case comparisons of binary search on 1,000,000 sorted items? ::: 20 (ceil of log base 2 of 1,000,000).


Connections