Edexcel International Advanced Level Computer Science, point 10.4.1
This is the coding side of recursion (5.1.3). In Unit 2 you may need to amend and write recursive subprograms. A recursive subprogram calls itself on a smaller version of the problem, until it reaches a base case.
The recipe
- Find the base case: the simplest input, with an answer you know.
- Find the recursive case: express the answer in terms of the same subprogram on a smaller input.
- Make sure each call moves towards the base case.
- Write the base case first (so the recursion stops).
def solve(problem):
if problem is simple: # base case
return the known answer
return combine(solve(smaller_problem)) # recursive case
Examples
Factorial
, with .
def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)
print(factorial(5)) # 120
Sum of the numbers 1 to n
def sum_to(n):
if n == 0:
return 0
return n + sum_to(n - 1)
print(sum_to(4)) # 10
Largest item in a list
def largest(items):
if len(items) == 1: # one item: it is the largest
return items[0]
rest = largest(items[1:]) # largest of the rest
return items[0] if items[0] > rest else rest
print(largest([3, 9, 4])) # 9
Sum of a list
def list_sum(items):
if not items: # empty list
return 0
return items[0] + list_sum(items[1:])
print(list_sum([3, 5, 2])) # 10
Reversing a string
def reverse(text):
if len(text) <= 1:
return text
return reverse(text[1:]) + text[0]
print(reverse("stack")) # kcats
Is a list in order?
def is_sorted(items):
if len(items) <= 1:
return True
if items[0] > items[1]:
return False
return is_sorted(items[1:])
print(is_sorted([2, 5, 5, 8])) # True
print(is_sorted([2, 9, 4])) # False
Counting the digits of a number
def count_digits(n):
if n < 10:
return 1
return 1 + count_digits(n // 10)
print(count_digits(472)) # 3
Greatest common divisor (Euclid)
def gcd(a, b):
if b == 0:
return a
return gcd(b, a % b)
print(gcd(18, 12)) # 6
Fibonacci (and memoisation)
def fib(n):
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
print(fib(10)) # 55
This repeats the same calls (fib(30) makes over 2.6 million calls). Memoisation stores results in a dictionary, so each value is worked out once:
memo = {}
def fib_memo(n):
if n in memo:
return memo[n]
result = n if n < 2 else fib_memo(n - 1) + fib_memo(n - 2)
memo[n] = result
return result
print(fib_memo(30)) # 832040 (only 59 calls)
Tracing a recursive call
count_digits(472):
| Call | Does | Returns |
|---|---|---|
count_digits(472) |
count_digits(47) |
|
count_digits(47) |
count_digits(4) |
|
count_digits(4) |
4 < 10: base case |
1 |
back in count_digits(47) |
2 | |
back in count_digits(472) |
3 |
The recursion limit
Each call uses a stack frame (1.2.4). Python limits the depth (about 1000 by default). Going past it raises RecursionError, which usually means a missing or unreachable base case.
def broken(n):
return n + broken(n - 1) # no base case
# broken(5) -> RecursionError: maximum recursion depth exceeded
You can see the limit with import sys; sys.getrecursionlimit().
Recursion or iteration?
| Recursion | Iteration | |
|---|---|---|
| Natural for | Trees, divide and conquer, self-similar problems | Simple counting and totals |
| Memory | Stack frame per call | Constant |
| Speed | Slower | Faster |
For a simple loop (such as a factorial), iteration is usually better. Recursion is worth it when the problem is naturally recursive (for example tree traversal, 18.2.8).
Worked example
Task: write a recursive function count_down(n) that returns a list from n down to 1, and trace count_down(3).
def count_down(n):
if n == 0:
return [] # base case: empty list
return [n] + count_down(n - 1) # recursive case
print(count_down(3)) # [3, 2, 1]
| Call | Returns |
|---|---|
count_down(0) |
[] (base case) |
count_down(1) |
[1] + [] = [1] |
count_down(2) |
[2] + [1] = [2, 1] |
count_down(3) |
[3] + [2, 1] = [3, 2, 1] |
Base case: n == 0. Each call reduces n by 1, so it reaches the base case.
Exam tip: write the base case first, and check that the recursive call is on a smaller input. Trace the calls going down and the values coming back up. If asked about problems, mention RecursionError (stack overflow) and repeated work (as with Fibonacci).
Check yourself
What two parts must every recursive subprogram have?
A base case that stops the recursion, and a recursive case that calls itself on a smaller problem.
What error occurs if a recursive function has no reachable base case?
A RecursionError (stack overflow) when the maximum depth is exceeded.
What does sum_to(3) return, and how many calls are made?
6, using 4 calls (n = 3, 2, 1 and 0).
How does memoisation speed up a recursive Fibonacci function?
It stores results in a dictionary, so each value is calculated only once instead of repeatedly.