B2.4.4 What recursion is
HL onlyCommand term: Explain1. A function that calls itself
Step through factorial(4). Each call waits on the call stack for a smaller version of the same problem, until the base case stops the chain. Then the answers flow back.
2. Recursion tree explorer
Every call is a node; its children are the calls it makes. Watch the calls happen in order, and count them. Some recursive designs are efficient; others repeat the same work again and again.
3. Quicksort: recursion that sorts
Quicksort picks a pivot, partitions the list into smaller and larger items, then recursively sorts each part. The brackets below the bars show the sub-lists still waiting on the call stack.
4. Recursive art: fractals
A fractal is made of smaller copies of itself, so the drawing code calls itself on each smaller copy. Increase the depth and watch the number of calls grow.
5. Traversing a binary tree
A binary search tree of titles. Each node's subtrees are smaller trees, so traversal is naturally recursive: visit the left subtree, the node, then the right subtree. (Trees in depth: B4, HL.)
6. Flip-card deck
Click to flip. Say the answer before you flip.
7. Recursion or iteration?
Is recursion a natural fit, or is a loop the better tool? Streaks of 3+ score double.
8. 45-second speed round: what does it return?
Expected output
Design notes (for your IA log)
Check my code
Practical tasks
Three tasks for this topic, from Average to Moderate to Challenging. Start with the first and work up. Each coding task gives you a starter file with tests already written; you write the missing code.
- Open your PyCharm project (or New Project → pure Python, name it
ib_cs_tasks). - Right-click the project → New → Python File, using the file name shown on the task.
- Press Copy starter and paste it in, or press Download .py.
- Right-click in the editor → Run (Windows Shift+F10, Mac Ctrl+R).
- Replace each
pass # your code herewith your own code. Do not change the code below# ---- tests ----. - Run the file and compare your output with Expected output. A crash or an
AssertionErrormeans something is not right yet. - Stuck for more than 10 minutes? Open the Hint. Open the Model solution only after a real attempt, then compare it with yours.
- Written parts: answer in your notebook first, then check the model answer.
Task 1: Watch factorial recurse
Write a recursive factorial(n, depth=0) that prints an indented line on the way in (factorial(3)) and on the way out (returns 6), so you can see the call stack grow and shrink. Identify the base case and the recursive case.
Starter file (write your code where it says pass # your code here):
def factorial(n, depth=0):
pass # your code here
# ---- tests ----
factorial(4)
Expected output when your code is correct:
factorial(4)
factorial(3)
factorial(2)
factorial(1)
returns 1
returns 2
returns 6
returns 24
Hint
Model solution
def factorial(n, depth=0):
print(" " * depth + f"factorial({n})")
if n <= 1:
result = 1
else:
result = n * factorial(n - 1, depth + 1)
print(" " * depth + f"returns {result}")
return result
# ---- tests ----
factorial(4)
Task 2: Digit sum and fast power
Write recursive digit_sum(n) (e.g. 4096 → 19) and power(x, n) that uses xn = (xn/2)² for even n and x · xn−1 for odd n. Count how many calls power(2, 1000) makes.
Starter file (write your code where it says pass # your code here):
calls = 0
def digit_sum(n):
pass # your code here
def power(x, n):
pass # your code here
# ---- tests ----
print(digit_sum(4096), digit_sum(7))
print(power(3, 5), power(2, 10))
calls = 0
print(power(2, 1000) == 2 ** 1000, calls)
Expected output when your code is correct:
19 7 243 1024 True 16
Hint
Model solution
calls = 0
def digit_sum(n):
if n < 10:
return n
return n % 10 + digit_sum(n // 10)
def power(x, n):
global calls
calls += 1
if n == 0:
return 1
if n % 2 == 0:
half = power(x, n // 2)
return half * half
return x * power(x, n - 1)
# ---- tests ----
print(digit_sum(4096), digit_sum(7))
print(power(3, 5), power(2, 10))
calls = 0
print(power(2, 1000) == 2 ** 1000, calls)
Task 3: Flatten a nested list
A reading list contains books and sub-lists of books, nested to any depth. Write recursive flatten(items) that returns all books in one flat list, and depth(items) that returns the deepest nesting level (a flat list has depth 1, an empty list depth 1).
Starter file (write your code where it says pass # your code here):
def flatten(items):
pass # your code here
def depth(items):
pass # your code here
# ---- tests ----
reading = ["Dune", ["Emma", ["Holes", "Kim"]], [], ["Matilda"]]
print(flatten(reading))
print(depth(reading), depth([]), depth([1, 2]), depth([[[[]]]]))
Expected output when your code is correct:
['Dune', 'Emma', 'Holes', 'Kim', 'Matilda'] 3 1 1 4
Hint
Model solution
def flatten(items):
out = []
for x in items:
if isinstance(x, list):
out.extend(flatten(x))
else:
out.append(x)
return out
def depth(items):
deepest = 0
for x in items:
if isinstance(x, list):
deepest = max(deepest, depth(x))
return 1 + deepest
# ---- tests ----
reading = ["Dune", ["Emma", ["Holes", "Kim"]], [], ["Matilda"]]
print(flatten(reading))
print(depth(reading), depth([]), depth([1, 2]), depth([[[[]]]]))
Learning objectives
By the end of this page you should be able to:
- Explain recursion: a function that solves a problem by calling itself on a smaller version of it, with a base case and a recursive case.
- Explain how the call stack makes recursion work, and why recursion uses memory that grows with its depth.
- Describe how quicksort uses recursion (pivot, partition, sort each part) and state its time complexity.
- Evaluate the advantages and limitations of recursion, including complexity and memory usage.
- Identify situations that suit recursion, such as fractal images, traversing binary trees and sorting algorithms.
What is recursion?
A recursive function solves a problem by calling itself on a smaller instance of the same problem. Every correct recursive function has:
- a base case: a simple version answered directly, without another call, which stops the recursion;
- a recursive case: the function calls itself with an input that moves closer to the base case.
def factorial(n):
if n <= 1: # base case
return 1
return n * factorial(n - 1) # recursive case: a smaller problem
Without a reachable base case the calls never stop, and the program crashes with a stack overflow (Python: RecursionError: maximum recursion depth exceeded, usually after about 1,000 calls).
The call stack
Each call pushes a stack frame holding its parameters, local variables and return point (B2.2.3, B2.3.4). Recursive calls wind the stack up until the base case; then each call returns its result to the one below and its frame is popped, as the stack unwinds. A recursion of depth d therefore needs d frames at the same time: O(d) memory.
Quicksort
- If the list has 0 or 1 items, it is already sorted (base case).
- Choose a pivot (here, the last item).
- Partition: move items smaller than the pivot to its left and larger ones to its right. The pivot is now in its final place.
- Recursively quicksort the left part and the right part.
Each level of recursion does about n comparisons in total. With good pivots the list halves each time, so there are about log₂ n levels: O(n log n) on average, and O(log n) stack space. With bad pivots (already sorted data with the last item as pivot) each partition removes only one item: n levels, O(n²) time and O(n) stack depth. Choosing a random or median-of-three pivot makes this rare.
Advantages and limitations
| Advantages | Limitations |
|---|---|
| Short, elegant code that mirrors the problem's definition | Each call has overhead (creating a frame), so it is often slower than a loop |
| A natural fit for self-similar structures: trees, nested folders, fractals | Memory grows with depth; deep recursion overflows the stack |
| Divide-and-conquer algorithms (quicksort, merge sort) are easy to express | Harder to trace and debug; a missing or wrong base case is easy to make |
| Removes the need to manage an explicit stack yourself | Naive designs can repeat work: naive Fibonacci makes O(2ⁿ) calls |
When to use it
Use recursion when a problem naturally breaks into smaller, similar subproblems and the depth is modest: fractal images, traversing binary trees, searching nested structures, divide-and-conquer sorting. Use a loop for simple repetition, long linear chains (summing a million numbers), or when memory is tight.
Use the 中文 button at the top to show or hide the Chinese terms.
| Term | 中文 | Meaning |
|---|
Choose an answer. You get instant feedback.
Score: 0 /
Write your answer first, then reveal the markscheme. These are exam-style practice questions written for this site.
1. Define recursion, and identify the base case and the recursive case in the function below. [3]
def count_down(n):
if n == 0:
print("Go!")
else:
print(n)
count_down(n - 1)
if n == 0: print("Go!"), which stops the recursion [1]; recursive case: count_down(n - 1), which moves n towards 0 [1].2. State the value returned by mystery(4), showing your working. [3]
def mystery(n):
if n == 1:
return 2
return 3 * mystery(n - 1) - 1
3. Explain how the call stack is used when factorial(3) is executed. [3]
4. Describe how quicksort sorts a list. [4]
5. Outline two limitations of using recursion. [4]
6. Explain why recursion is well suited to traversing a binary tree. [3]