B2.4.5 Writing and tracing recursive algorithms
HL onlyCommand terms: Construct, Trace1. Recursion tracer
Pick a function and an argument, then step through every call and return. The trace table records each call's arguments and what it returns; the stack shows which calls are still waiting.
2. On the way down, or on the way back up?
The only difference between these functions is where the print is: before the recursive call, or after it. Predict both outputs, then run.
Print before the call
Print after the call
3. Recursion builder
Construct a recursive function by choosing its base case, the base value and the recursive step. Your function is run on the test cases, and you see what Python would do, including RecursionError, IndexError and wrong answers.
4. Loop or recursion: the same algorithm twice
Every simple non-branching recursion can be written as a loop. The loop condition is the opposite of the base case, the loop variable becomes the parameter, and the accumulator becomes the combine step on the way back.
Iterative
Recursive
5. Flip-card deck
Click to flip. Say the answer before you flip.
6. Predict the output
Trace each recursive snippet. Streaks of 3+ score double.
7. 45-second speed round: how many calls?
Count every call, including the first one and the base case.
Expected output
Think about it
- Which base case does
is_palindromeneed so that both odd-length and even-length words stop safely? - Why does
binary_searchpasslowandhighinstead of slicing the list? What would slicing do to the index it returns? - How many calls does
digit_summake for a 17-character ISBN-13 with hyphens? Is that a problem?
Trace by hand: digit_sum("9-07")
Fill in what each call returns. Start at the base case and work upwards.
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: Recursive binary search
Rewrite binary search recursively: bsearch(items, target, low, high) returns the index or −1. Identify the two base cases.
Starter file (write your code where it says pass # your code here):
def bsearch(items, target, low, high):
pass # your code here
# ---- tests ----
data = [2, 5, 8, 12, 16, 23, 38, 56, 72, 91]
print([bsearch(data, t, 0, len(data) - 1) for t in [23, 2, 91, 7]])
Expected output when your code is correct:
[5, 0, 9, -1]
Hint
Model solution
def bsearch(items, target, low, high):
if low > high:
return -1
mid = (low + high) // 2
if items[mid] == target:
return mid
if items[mid] < target:
return bsearch(items, target, mid + 1, high)
return bsearch(items, target, low, mid - 1)
# ---- tests ----
data = [2, 5, 8, 12, 16, 23, 38, 56, 72, 91]
print([bsearch(data, t, 0, len(data) - 1) for t in [23, 2, 91, 7]])
Task 2: Recursive palindrome check
Write recursive is_palindrome(s) that ignores case, spaces and punctuation. Clean the string once in a wrapper, then recurse on a helper that compares the first and last characters.
Starter file (write your code where it says pass # your code here):
def _check(s):
pass # your code here
def is_palindrome(text):
pass # your code here
# ---- tests ----
for t in ["racecar", "Never odd or even", "A man, a plan, a canal: Panama!", "ShelfWise", ""]:
print(f"{t!r}: {is_palindrome(t)}")
Expected output when your code is correct:
'racecar': True 'Never odd or even': True 'A man, a plan, a canal: Panama!': True 'ShelfWise': False '': True
Hint
Model solution
def _check(s):
if len(s) <= 1:
return True
if s[0] != s[-1]:
return False
return _check(s[1:-1])
def is_palindrome(text):
cleaned = "".join(ch.lower() for ch in text if ch.isalnum())
return _check(cleaned)
# ---- tests ----
for t in ["racecar", "Never odd or even", "A man, a plan, a canal: Panama!", "ShelfWise", ""]:
print(f"{t!r}: {is_palindrome(t)}")
Task 3: Towers of Hanoi
Move n discs from peg A to peg C using peg B, never placing a larger disc on a smaller one. Write recursive hanoi(n, source, target, spare, moves) that appends each move as a string like "A->C". Print the moves for 3 discs, then show that the number of moves is 2n − 1. Finally, write check(n, moves) that simulates the moves and confirms that no rule is broken.
Starter file (write your code where it says pass # your code here):
def hanoi(n, source, target, spare, moves):
pass # your code here
def check(n, moves):
pass # your code here
# ---- tests ----
m = []
hanoi(3, "A", "C", "B", m)
print(m)
for n in range(1, 11):
m = []
hanoi(n, "A", "C", "B", m)
assert len(m) == 2 ** n - 1 and check(n, m)
print("2^n - 1 moves, all legal, for n = 1..10")
Expected output when your code is correct:
['A->C', 'A->B', 'C->B', 'A->C', 'B->A', 'B->C', 'A->C'] 2^n - 1 moves, all legal, for n = 1..10
Hint
Model solution
def hanoi(n, source, target, spare, moves):
if n == 0:
return
hanoi(n - 1, source, spare, target, moves)
moves.append(f"{source}->{target}")
hanoi(n - 1, spare, target, source, moves)
def check(n, moves):
pegs = {"A": list(range(n, 0, -1)), "B": [], "C": []}
for m in moves:
a, b = m.split("->")
if not pegs[a]:
return False
disc = pegs[a].pop()
if pegs[b] and pegs[b][-1] < disc:
return False
pegs[b].append(disc)
return pegs["C"] == list(range(n, 0, -1))
# ---- tests ----
m = []
hanoi(3, "A", "C", "B", m)
print(m)
for n in range(1, 11):
m = []
hanoi(n, "A", "C", "B", m)
assert len(m) == 2 ** n - 1 and check(n, m)
print("2^n - 1 moves, all legal, for n = 1..10")
Learning objectives
By the end of this page you should be able to:
- Construct simple, non-branching recursive functions by identifying the base case, the recursive case and how the results are combined.
- Trace recursive calls with a trace table and the call stack, showing the calls winding down and the returns unwinding, and determine the return value.
- Distinguish between work done before the recursive call (on the way down) and after it (on the way back up), and predict the order of output.
- Convert between simple iterative and recursive versions of an algorithm.
- Identify and correct common errors: a missing or unreachable base case, a step that does not shrink the problem, and a missing return.
A recipe for constructing a recursive function
- Find the smallest case whose answer you know directly: n = 0, an empty string, an empty list. That is the base case.
- Make the problem one step smaller: n - 1, n // 10, s[1:], items[1:], a smaller range.
- Assume the recursive call works for the smaller problem (the "leap of faith"), and work out how to combine its answer with the current step.
- Check that every possible input eventually reaches the base case.
def total(items):
if len(items) == 0: # 1. base case
return 0
return items[0] + total(items[1:]) # 2. smaller problem, 3. combine
def reverse(s):
if len(s) <= 1:
return s
return reverse(s[1:]) + s[0] # reverse the rest, then add the first char
def binary_search(items, target, low, high):
if low > high: # base case: empty range, not found
return -1
mid = (low + high) // 2
if items[mid] == target: # base case: found
return mid
if items[mid] < target:
return binary_search(items, target, mid + 1, high) # only ONE call runs
return binary_search(items, target, low, mid - 1)
Tracing
Use a table with one row per call: the arguments, whether it is the base case, the recursive call it makes, and the value it returns. Fill the calls top to bottom (winding), then fill the returns bottom to top (unwinding).
| Call | s | Base case? | Calls | Returns |
|---|---|---|---|---|
| 1 | "abc" | no | reverse("bc") + "a" | "cb" + "a" = "cba" |
| 2 | "bc" | no | reverse("c") + "b" | "c" + "b" = "cb" |
| 3 | "c" | yes | none | "c" |
Before or after the call?
Statements before the recursive call run as the calls go down (first call first). Statements after it run as the calls return (last call first). That is why printing after the call reverses the order.
Common errors
- No base case, or one that can be jumped over (testing
n == 0while subtracting 2 from an odd n): RecursionError. - The recursive call uses the same argument (
f(n)instead off(n - 1)): RecursionError. - Forgetting return in front of the recursive call: the function returns None.
- A wrong base value (returning 1 instead of 0 for a sum) makes every answer wrong by the same amount.
In Java the structure is the same: static int total(int[] a, int i) { if (i == a.length) return 0; return a[i] + total(a, i + 1); }, passing an index instead of slicing.
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. Construct a recursive Python function total(items) that returns the sum of a list of numbers. [4]
2. Trace reverse("abc") using the function on the Learn tab, showing each call and the value it returns. [4]
3. State the output of show(3). [3]
def show(n):
if n == 0:
print("*")
return
print(n)
show(n - 1)
print(n)
4. The function below should return the sum of the even numbers from n down to 0. Identify the error for evens(5) and construct a correction. [3]
def evens(n):
if n == 0:
return 0
return n + evens(n - 2)
if n <= 0: return 0 [1] and skip odd values, e.g. if n % 2 == 1: return evens(n - 1) before the existing return [1].5. Construct a recursive function count_digits(n) that returns the number of digits in a positive integer. [4]
if n < 10: return 1 [1]; recursive call on n // 10 [1]; returning 1 + that result [1]; correct overall structure, e.g. returns 4 for 2026 [1].6. Construct a recursive version of this iterative function, and state one disadvantage of your version. [3]
def power(b, e):
result = 1
for i in range(e):
result = result * b
return result
if e == 0: return 1 [1]; return b * power(b, e - 1) [1]; disadvantage: uses O(e) stack frames / extra call overhead / risk of RecursionError for large e, where the loop uses O(1) memory [1].