OCR H446, section 2.2.1 (b)
Recursion is when a subroutine calls itself. It solves a problem by reducing it to a smaller version of the same problem.
The two essential parts
- A base case: a situation simple enough to answer directly, with no more recursive calls. It stops the recursion.
- A recursive case: the subroutine calls itself with a smaller or simpler argument, which moves towards the base case.
Without a base case, or if the argument doesn't get closer to it, the calls never stop.
Example: factorial
, and .
def factorial(n):
if n == 0: # base case
return 1
return n * factorial(n - 1) # recursive case
OCR pseudocode:
function factorial(n)
if n == 0 then
return 1
else
return n * factorial(n - 1)
endif
endfunction
Tracing factorial(3)
Calls go down until the base case, then the results come back up:
factorial(3)
= 3 * factorial(2)
= 2 * factorial(1)
= 1 * factorial(0)
= 1 <- base case
= 1 * 1 = 1
= 2 * 1 = 2
= 3 * 2 = 6
The call stack
Each call needs its own copy of its parameters, local variables and return address. These are stored in a stack frame on the call stack (1.1.1 and 2.3.1 (e)).
- A frame is pushed on each call, and popped when it returns.
- The stack has a limited size. If recursion goes too deep (or never ends) the stack overflows, and the program crashes with a stack overflow error. In Python this is
RecursionError.
Another example: sum of a list
def total(items):
if len(items) == 0: # base case: nothing left
return 0
return items[0] + total(items[1:]) # smaller list
Example with two recursive calls: Fibonacci
def fib(n):
if n < 2: # base cases: fib(0)=0, fib(1)=1
return n
return fib(n - 1) + fib(n - 2)
This is simple to write but inefficient: fib(30) makes more than 2.6 million calls, because the same values are worked out many times (see memoisation, 2.1.2 (c)).
Recursion compared with iteration
The same problem can often be solved either way.
def factorial_iter(n):
result = 1
for i in range(2, n + 1):
result = result * i
return result
| Recursion | Iteration | |
|---|---|---|
| Code | Often shorter and clearer for naturally recursive problems | Can be longer for those |
| Memory | Uses stack space for every call: each call makes new copies of its parameters and local variables | Uses little extra memory: the loop reuses the same variables |
| Speed | Slower (call overhead) | Usually faster |
| Risk | Stack overflow if too deep or no base case | Infinite loop if the condition never fails |
| Best for | Trees, graphs, divide and conquer, backtracking | Simple repetition over a known range |
| Termination | Reaches the base case | The loop condition becomes false |
Problems that are naturally recursive include tree traversal, quick sort and merge sort, binary search, the Towers of Hanoi, and maze solving. Any recursive algorithm can be rewritten with a loop (and sometimes a stack), and the other way round.
Worked example
Task: write a recursive function to count down from n to 1, then say "Go!". Show the calls for countdown(3).
def countdown(n):
if n == 0:
print("Go!")
else:
print(n)
countdown(n - 1)
countdown(3)
| Call | n |
Output | Next |
|---|---|---|---|
countdown(3) |
3 | 3 | calls countdown(2) |
countdown(2) |
2 | 2 | calls countdown(1) |
countdown(1) |
1 | 1 | calls countdown(0) |
countdown(0) |
0 | Go! | base case: returns |
The output is 3, 2, 1, Go!. At its fullest the stack holds four countdown frames (on top of the main program's). If the n == 0 test were missing, n would go negative forever and the program would crash with a stack overflow.
Exam tip: always point out the base case and show that each call gets closer to it. When comparing with iteration, mention stack memory, and the risk of stack overflow. When tracing, show the calls going down and the values returning back up.
Check yourself
What is recursion?
When a subroutine calls itself, solving a problem by reducing it to a smaller version of the same problem.
What is a base case, and why is it needed?
A case that can be answered directly, without another recursive call. It stops the recursion; without it the calls would never end.
What happens if a recursive function has no base case?
It keeps calling itself, filling the call stack until a stack overflow error stops the program.
Give one advantage and one disadvantage of recursion compared with iteration
Advantage: shorter, clearer code for naturally recursive problems such as tree traversal. Disadvantage: uses more memory (a stack frame per call) and risks stack overflow.