Recursion: base case and recursive case
Write recursive functions with a base case and a smaller recursive call, and trace them on the call stack.
It opens on
4! is 4 × 3 × 2 × 1. Can a function that computes 4! use 3! without knowing how 3! is worked out?
Why it matters
Recursion is how many problems are most naturally written, folders inside folders, trees, divide and conquer searches and sorts, and tracing a recursive call on the stack is a standard exam question in a first programming course.
Good to know first
- Scope and the call stack: each call has its own frame, and a frame leaves the stack when it returns
- Defining functions: return sends a value back to the caller
- Values and expressions: n // 10 drops the last digit and n % 10 is the last digit
Step by step
A function that calls itself
Write factorial recursively with a base case and a recursive case, and say why each call is smaller.
So 4! can be found from 3! without redoing how 3! was found. That answers the opening question, yes, and it is the idea of recursion, a function that solves a problem using a smaller copy of the same problem.
A common mix-up
A recursive function runs the same code on the same data forever.
In fact: Each call gets a smaller argument, and the base case stops the chain.
Tracing on the stack
Trace factorial(4) and sum_digits(4729) on the call stack, giving each frame's n and each returned value.
factorial(0) is the base case and returns 1. Its frame leaves the stack, and factorial(1) can now compute 1 × 1 = 1.
A common mix-up
Factorial(4) multiplies 4 × 3 first, on the way down.
In fact: No multiplication can happen until factorial(0) returns; the products are done on the way back up, 1, 2, 6, 24.
Missing base case
Explain the RecursionError from a missing or unreachable base case, and check that every call moves towards the base case.
The traceback said the same line repeated 996 more times. Python's limit is 1000 frames, sys.getrecursionlimit() printed 1000, and it raises the error rather than let the stack grow without end.
A common mix-up
A RecursionError means the computer ran out of memory.
In fact: It means Python's limit of about 1000 frames was hit, usually by a missing or unreachable base case.
Try it
Using factorial, what is factorial(6)?Answer
720, since 6 × 120
Hint: 5! is 120
Trace sum_digits(80) and give the result.Answer
0 + sum_digits(8), and 8 is the base case, so 8
Hint: 80 % 10 is 0
countdown(n) prints n and then calls countdown(n - 1), and when n is 0 it prints liftoff instead. What does countdown(3) print?Answer
3, 2, 1, liftoff, each on its own line
Hint: 0 is the base case
Using the table, what is 4!, and which row did you use?Answer
24, which is 4 times 3!, and 3! is 6.
How many frames of factorial are on the stack at the deepest point?Answer
5, for n = 4, 3, 2, 1 and 0.
