Recursion
Functions That Call Themselves
- Recursions can be used to solve problems that involve repetition
- We can create a countdown time using a loop or a recursion
While Loop
def countdown(number):
while number >= 0:
print(number)
number -= 1
Recursion
def countdown(number):
print(number)
# Base case
if number == 0:
return
else:
# Recursive call
countdown(number - 1)
- The base case is the condition where the function should stop calling itself
- When `number` is 0, the function returns without calling itself again.
- Every recursive function needs at least one base case to prevent infinite recursion (stack overflow).
Tracing Recursive Code
A factorial is the product of all positive integers up to a number:
\[3! = 3 × 2 × 1 = 6\]
def factorial(number):
# Base case: number < 1
if number <= 1:
return 1
# Call n * factorial(n - 1)
return number * factorial(number - 1)
Recursive code is read by starting from the base case and building your understanding upwards:
- Identify the base case (when does it stop?)
factorial(1)returns1
- Walk through the base case
- Work backwards from there
factorial(2)returns2 * factorial(1)=2 * 1=2factorial(3)returns3 * factorial(2)=3 * 2=6
Tracing factorial(3)
Every time a function is called, Python creates a new stack frame with its own local variables
factorial(3)creates a frame wherenumber = 3- That call triggers
factorial(2), which creates a new frame wherenumber = 2 - Finally
factorial(1)is called wherenumber = 1where the base case is met
When a frame returns, the result is returned to the frame that called it, and then the frame is removed from the stack.
The Call Stack
- Python tracks frames using a call stack
- The stack is both a kind of data structure and a region of memory Python uses to manage functions and code execution
- A stack is a Last in First Out (LIFO) list of stack frames waiting to complete
- Each call pushes a new frame onto the stack.
- When a call completes, its frame is popped off and the result is passed back to the caller.
- The last frame pushed is always the first one completed (LIFO)
Stack Overflow
The following recursive overflow() function does not have a base case:
def overflow():
overflow()
Each call pushes a new frame onto the stack, but no frame ever completes: and there no base case to stop the chain.
The stack grows until Python runs out of memory and raises a RecursionError (default limit is 1000 frames). Base cases prevent this from happening.
Repeatedly Execute
Some recursive functions repeatedly perform a task. The pattern to common to these functions is that the last line is a simple recursive call.
- The following function prints a triangle using stars
def print_stars(n):
# Base case: no more rows
if n <= 0:
return
print('*' * n)
print_stars(n - 1)
print_stars(4)
**** *** ** *
- These functions perform an action (print, modify, etc.) and then make a simple recursive call
Pattern: Execute an action, then recurse on remaining elements.
Calculations
The second category of recursive functions computes a result based on a subproblem: a smaller version of the same problem.
- The
factorialis one example of this type of function:n * factorial(n-1)uses the result from a subproblem
def factorial(number):
# Base case: number < 1
if number <= 1:
return 1
# Call n * factorial(n - 1)
return number * factorial(number - 1)
print(factorial(3))
6
- The base case handles the smallest version of the problem
- The recursive step calls the function on a smaller subproblem
- Return values allow the functions to complete the work
Passing Extra Parameters
A technique we can use with recursion is to pass additional parameters with the function call:
- Track position in a sequence
- Accumulate results
- Pass state between recursive calls using the accumulator
def running_sum(lst, acc=0):
# Base case: empty list
if not lst:
return []
else:
new_sum = acc + lst[0]
return [new_sum] + running_sum(lst[1:], new_sum)
print(running_sum([1, 2, 3]))
[1, 3, 6]
- The running totals are computed on the way down, and the result list is assembled from the return values
Recursive Data Structures
- A Linked List is a data structure where each element contains a link to the next element in a sequence
- Each element contains a
valueand a reference to therestof the list - Linked lists are a recursive data structure because each element contains a value, and a reference to the
restof the list
Here is an approximation of a simple linked data structure we can use to use to understand recursive processing. Each tuple is a pair and the second element references the rest of the list:
linked_list = (7, (8, (9, None)))
We can traverse the linked list by using a recursive function that visits the first element and then continues to visit the rest of the elements until it reaches the end:
def first(lst):
return lst[0]
def rest(lst):
return lst[1]
def traverse(lst):
print(first(lst))
if rest(lst) is None:
return
traverse(rest(lst))
traverse(linked_list)
Recursive Processing
Once we are able to traverse this data structure, a number of different recursive operations are possible.
Length
def length(lst):
if lst is None:
return 0
return 1 + length(rest(lst))
print(length(linked_list))
3
- The base case is an empty list, where
0is returned - We add
1each time we encounter an element and the subproblem is calling the function on the rest of the list
Sum
We can perform a similar operation for calculating the sum by adding the value of the first element to the rest of the list.
def sum_list(lst):
if lst is None:
return 0
return first(lst) + sum_list(rest(lst))
print(sum_list(linked_list))
24
Produce a New List
A tuple can be returned to retain same recursive data structure, but with the elements modified. The modification is performed on the first element and then recursivley called on the rest of the elements.
def double(lst):
if lst is None:
return None
return (first(lst) * 2, double(rest(lst))) # tuple
print(double(linked_list))
(14, (16, (18, None)))
Filter a List
A filtering function can be used to produce a new list.
def filter_odd(lst):
if lst is None:
return None
if first(lst) % 2 == 1:
# Include first number if odd and recurse on rest
return (first(lst), filter_odd(rest(lst)))
else:
# Otherwise recurse on rest of the list
return filter_odd(rest(lst))
print(filter_odd(linked_list))
(7, (9, None))
Accumulator
An accumulator can be used to pass along the max value encountered whilst traversing the list.
def list_max(lst, acc=None):
if lst is None:
return acc
# Is the current element bigger than what
# we have already seen?
if acc is None or first(lst) > acc:
acc = first(lst)
return list_max(rest(lst), acc)
print(list_max(linked_list))
9
Measuring Efficiency
- Big O notation describes how the time (or memory) an algorithm needs grows as the input size grows.
| Notation | Name | Example |
|---|---|---|
| \(O(1)\) | Constant | Looking up a dictionary key |
| \(O(\log n)\) | Logarithmic | Binary search (divide by two) |
| \(O(n)\) | Linear | Looping through a list once |
| \(O(n^2)\) | Quadratic | Nested loops |
| \(O(2^n)\) | Exponential | Naive recursive Fibonacci |
Every recursive call adds a frame to the call stack, and some recursive functions call themselves multiple times per call.
countdown(n)makes one call per step: \(O(n)\)factorial(n)makes one call per step: \(O(n)\)fib(n)branches into two calls per step: \(O(2^n)\)
The Fibonacci Sequence
Consider the Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21…
Each number is the sum of the previous two numbers. This is a recursive sequence, each position is dependent on calculating the previous two positions.
def fib(n):
if n < 2:
return n
return fib(n - 2) + fib(n - 1)
There is a problem, calculating this recursively needs a lot of recursive calls:
count = 0
def fib(n):
global count
count += 1
if n < 2:
return n
return fib(n - 2) + fib(n - 1)
fib(6)
print("Function called:", count, "times")
Function called: 25 times
Tracing Fibonacci
If we trace the naive implementation of fib(6):
Problem: fib(3) is computed multiple times, fib(2) is computed many more times,
These are overlapping subproblems: the same calculations are repeated over and over, resulting in \(O(2^n)\) time or exponential growth.
Dynamic Programming
Memoisation means storing previously computed results so we never calculate the same thing twice.
- First time we compute
fib(3), store the result in a dictionary - Next time we need
fib(3), look it up instead of recomputing
def fib(n, memo={}):
if n < 2:
return n
# Only calculate if n is not in memo
if n not in memo:
memo[n] = fib(n - 2, memo) + fib(n - 1, memo)
return memo[n]
We pass the memo dictionary as an accumulator to each recursive call so that all calls share it.
Remember that Python function signatures are cached, how does that help here?
Memoised Fibonacci
With memoisation, the complexity of fib(6) goes from \(O(2^n)\) to \(O(n)\):
count = 0
def fib(n, memo={}):
global count
count += 1
if n < 2:
return n
if n not in memo:
memo[n] = fib(n - 2, memo) + fib(n - 1, memo)
return memo[n]
fib(6)
print("Function called:", count, "times")
Function called: 11 times
Functools Cache
Python provides a cache decorator in the functools library for automatic memoisation:
from functools import cache
@cache
def fib(n):
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
print(fib(10)) # 55
print(fib(50)) # 12586269025
The @cache decorator automatically stores and retrieves results
Replacing Recursion with Iteration
Not all problems need a recursive solution, the iterative version of fibonnaci is faster
def fib(n):
if n == 0:
return 0
a = 0 # fib(0)
b = 1 # fib(1)
for _ in range(1, n):
a, b = b, a + b
return b
Start with the base cases (0, 1) and build up to n using a loop.
- Also \(O(n)\) time, like memoisation
- Has the added benefit that there is no recursion limit
- Not all problems are this clean: some bottom-up solutions still need arrays or tables to store intermediate results
When to Use Recursion
Recursion
- Problem naturally divides into smaller versions of itself
- You need to traverse tree/graph structures
- The iterative solution would be significantly harder to write
Iteration
- Simple sequential processing
Good Uses for Recursion
- Tree traversal (file systems, DOM traversal, organisation charts)
- Divide-and-conquer algorithms (merge sort, quicksort)
- Backtracking problems (mazes, puzzles)
- Mathematical definitions (factorials, combinations)
Exercise
Low to High
Write a recursive function start_to_end that accepts a start and end parameter and prints out the numbers in that range:
start_to_end(1, 3)
# 1
# 2
# 3
List Flattening
Flatten a nested list [[1, 2], [3, [4, 5]], 6] → [1, 2, 3, 4, 5, 6]
- Check if first element is a list
- If yes, flatten it and concatenate with rest
- If no, add it to flattened rest
Hint: You can use the Iterable ABC from collections to check if an object is iterable in Python. This will let you know if you can flatten any kind of object:
from collections.abc import Iterable
if isinstance(i, Iterable):
# i is iterable
Python 3.15 lets you write [x* for x in nested_list]