Home › Theme B › B2 › B2.4 › B2.4.5

B2.4.5 Writing and tracing recursive algorithms

HL onlyCommand terms: Construct, Trace

1. 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.

Function:

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.

n =

Print before the call

Print after the call

Predict first.

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.

Task:
Choose all three parts, then run.

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.

Algorithm:

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.

Round 0/10Score 0Streak 0Best 0
Press start!

7. 45-second speed round: how many calls?

Count every call, including the first one and the base case.

Time 45sScore 0Streak 0Best 0
Press start!
ShelfWise · Sprint 4, task 5 (HL). Write five small recursive tools for ShelfWise. Each one must have a clear base case and a recursive case that makes the problem smaller, with no loops. Then trace one of them by hand.

Expected output

4 0 enuD 0 True False 5 -1 29

Think about it

  • Which base case does is_palindrome need so that both odd-length and even-length words stop safely?
  • Why does binary_search pass low and high instead of slicing the list? What would slicing do to the index it returns?
  • How many calls does digit_sum make 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

    Sprint 4 complete. Next sprint (B2.5.1): ShelfWise saves and loads its catalogue with files.

    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.

    Set up in PyCharm
    1. Open your PyCharm project (or New Project → pure Python, name it ib_cs_tasks).
    2. Right-click the project → New → Python File, using the file name shown on the task.
    3. Press Copy starter and paste it in, or press Download .py.
    4. Right-click in the editor → Run (Windows Shift+F10, Mac Ctrl+R).
    How the tasks work
    1. Replace each pass # your code here with your own code. Do not change the code below # ---- tests ----.
    2. Run the file and compare your output with Expected output. A crash or an AssertionError means something is not right yet.
    3. Stuck for more than 10 minutes? Open the Hint. Open the Model solution only after a real attempt, then compare it with yours.
    4. Written parts: answer in your notebook first, then check the model answer.
    Average

    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):

    File: b2_4_5_average.py
    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
    Base cases: the range is empty, or items[mid] is the target.
    Model solution
    File: b2_4_5_average_solution.py
    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]])
    
    Moderate

    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):

    File: b2_4_5_moderate.py
    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
    A string is a palindrome if its ends match and the middle is a palindrome.
    Model solution
    File: b2_4_5_moderate_solution.py
    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)}")
    
    Challenging

    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):

    File: b2_4_5_challenging.py
    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
    To move n discs: move n − 1 out of the way, move the biggest, then move the n − 1 back on top.
    Model solution
    File: b2_4_5_challenging_solution.py
    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:

    1. Construct simple, non-branching recursive functions by identifying the base case, the recursive case and how the results are combined.
    2. 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.
    3. 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.
    4. Convert between simple iterative and recursive versions of an algorithm.
    5. 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

    1. Find the smallest case whose answer you know directly: n = 0, an empty string, an empty list. That is the base case.
    2. Make the problem one step smaller: n - 1, n // 10, s[1:], items[1:], a smaller range.
    3. 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.
    4. 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).

    CallsBase case?CallsReturns
    1"abc"noreverse("bc") + "a""cb" + "a" = "cba"
    2"bc"noreverse("c") + "b""c" + "b" = "cb"
    3"c"yesnone"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 == 0 while subtracting 2 from an odd n): RecursionError.
    • The recursive call uses the same argument (f(n) instead of f(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]

    Function header with one parameter [1]; base case: if the list is empty, return 0 [1]; recursive call on a smaller list, e.g. items[1:] [1]; combine: return items[0] + total(items[1:]) [1].

    2. Trace reverse("abc") using the function on the Learn tab, showing each call and the value it returns. [4]

    reverse("abc") calls reverse("bc") [1]; reverse("bc") calls reverse("c") [1]; reverse("c") is the base case and returns "c" [1]; returns unwind: "c" + "b" = "cb", then "cb" + "a" = "cba" [1].

    3. State the output of show(3). [3]

    def show(n):
        if n == 0:
            print("*")
            return
        print(n)
        show(n - 1)
        print(n)
    3, 2, 1 printed on the way down [1]; * at the base case [1]; then 1, 2, 3 on the way back up [1]. Output (one per line): 3 2 1 * 1 2 3.

    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)
    For odd n the values go 5, 3, 1, -1, ... and never equal 0, so the base case is never reached: RecursionError (odd numbers would also be added) [1]. Correction: use 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]

    Base case: 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].