iq.lab
Python starts when a code cell comes near or you run one
08 Recursion and trees

Lesson 1 of 5

Recursion and the call stack

A recursive function answers a question by asking itself the same question about something smaller, until it reaches a case it can answer outright. Watch the call stack grow and shrink, learn to trust the smaller call, and make slow recursion fast with a memo and with halving.

About 1 hour 40 minutes, with the 2 problems worked in it
By the end you can
  • Trace a recursive function and say which calls are waiting on the call stack at every step

  • Write a recursive function from a base case and the smaller calls you trust, combining their answers in a plain loop

  • Count the calls and the depth of a recursion, and state its time and its stack space

  • Spot a recursion that repeats work, and remove the repeats with a memo

  • Compute a power in about log n calls by halving

Your company's org chart is a table of (employee, manager) rows. How many people work under Dana, directly or through someone else? Dana has three direct reports. Some of them manage people, some of those manage people, and nothing tells you how many levels there are.

A for loop walks a list one item at a time, but this question has a different shape. The answer for Dana is built from the same question asked about each person she manages: everyone under Dana is her direct reports plus everyone under each of them. A function that answers a question by calling itself on a smaller piece of it is called recursive.

You have met recursion in passing: sum_to in module 2 and merge sort in module 6 both call themselves. This lesson teaches it properly. Trees, the rest of this module, are built the same way: a node with smaller trees under it. So we learn the tool on plain numbers first, where every step can be checked by hand.

A function that calls itself

Factorial is the classic first example. The factorial of 4 is 4 × 3 × 2 × 1 = 24: the factorial of a whole number n multiplies every whole number from n down to 1. Group it differently: 4 × (3 × 2 × 1), and the part in parentheses is the factorial of 3. So factorial(4) is 4 * factorial(3), and in general factorial(n) is n * factorial(n - 1).

On its own that rule never stops: 3 needs 2, which needs 1, which needs 0, and on into the negatives. It needs an input whose answer we know outright: the factorial of 1 is 1. Every recursive function has two parts:

  • The base case: an input small enough to answer with no further calls. Here, n <= 1 returns 1. The <= also catches 0, whose factorial is 1 by definition.
  • The recursive case: call the same function on a smaller input, then use its answer. Here, n * factorial(n - 1).

Before you step through factorial(3), guess: at the busiest moment, how many factorial boxes are on screen at once?

Step throughfactorial(3) calls itself
Step 1 of 13
Line 1 is about to run.
def factorial(n):
if n <= 1:
return 1
rest = factorial(n - 1)
return n * rest
Names
no names yet
Output
(nothing printed yet)

Each call gets its own box of names, called a frame. The call for 3 and the call for 2 both have a name n, and they never mix. When a call returns, its frame disappears and its answer lands in the frame that asked, as rest.

The answer is built on the way back up. On the way down the calls only ask. The base case's return 1 is the first answer, then each waiting call finishes in turn: 2 × 1 = 2, then 3 × 2 = 6.

Order is what trips people up. This function prints on the way down and again on the way up.

PredictDown, then up

This function prints once on the way down and once on the way back up. Type exactly what visit(2) prints, one line per print.

def visit(n):
    if n == 0:
        print("base")
        return
    print("down", n)
    visit(n - 1)
    print("up", n)

visit(2)

How deep the stack goes

How does Python keep the waiting calls in order? The calls that have started and not finished wait in a pile, newest on top, called the call stack. It is a stack in the sense of module 5: last in, first out. Only the top call runs. Each call below it is paused on the line that made the call, and it resumes when the call above it returns.

The figure below draws each call of factorial(4) as a box, one level below the call that made it, with the call stack and the code under it. Each call is two steps: one when it is made, one when it returns. Watch three readouts: calls made, current depth (calls on the stack now) and max depth (the most at once so far).

The most calls on the stack at once is the recursion's depth, the figure's max depth. Every waiting frame holds memory, so a recursion uses O(depth) extra space for its stack, even with no list in the code. factorial(n) goes n deep: O(n) space, where a loop keeping one running product needs O(1).

The stack has a ceiling. Plain Python stops at about 1,000 nested calls by default and raises RecursionError. sys.setrecursionlimit (in the standard sys module) raises the limit, and this lab runs with 5,000. Set it too high and Python itself can crash, so it is not a cure. A recursion that goes one level deeper per item is fine on 100 items and fails on 100,000. When the depth grows with the input, say so and name the fix: a loop, or a recursion that halves (the last section).

The base case decides where the chain stops, so count a depth exactly.

Work it outOne more frame

This factorial uses n == 0 as its base case. The factorial of 0 is defined as 1, so every answer is the same as before.

def factorial(n):
    if n == 0:
        return 1
    return n * factorial(n - 1)

At the deepest point of factorial(5), how many factorial calls are on the call stack at once?

calls on the stack

Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.

The other way to hit the ceiling is a recursion that never reaches its base case.

Quick checkA base case the calls jump over

What happens when you call count_down(5)?

def count_down(n):
    if n == 0:
        return "done"
    return count_down(n - 2)

Choose one answer, then check.

So far: a recursive function has a base case and a recursive case on a smaller input. Each call gets a frame; unfinished frames wait on the call stack, and only the top one runs. The depth costs space, and Python caps it.

The leap of faith

Tracing every frame works for factorial(3), not for a thousand calls, and you do not need it to. Write and check a recursive function by trusting the smaller call. This is called the leap of faith: assume factorial(n - 1) returns the right answer, and ask only whether this call uses it correctly.

Three checks replace the whole trace:

  1. The base case is right. factorial(1) returns 1, the factorial of 1.
  2. Every call moves toward a base case. n − 1 is smaller than n, and counting down by one from any whole number above 1 lands on 1.
  3. The combine step is right, assuming the smaller answer is. If rest is the factorial of n − 1, then n * rest is the factorial of n.

If all three hold, every call returns the right answer: the base case is right, so the call above it is right, and so on all the way up. It is the loop promise from module 1 again, kept by every call instead of every pass.

Now build one from shuffled lines. power(x, n) returns x to the power n: n copies of x multiplied together, and 1 when n is 0. The leap of faith: if power(x, n - 1) is right, one more x makes power(x, n).

Put in orderA power, one step at a time

Put the lines in order to build power(x, n), which returns x to the power n (n copies of x multiplied together) for n of 0 or more. Any number to the power 0 is 1. Indentation is already part of each line. Two of the lines do not belong.

Your program

Add lines from the list below, in order.

    Unused lines (some do not belong)
    • return x
    • return 1
    • return x * power(x, n - 1)
    • if n == 0:
    • def power(x, n):
    • return x * power(x, n)

    Then write one yourself. The digit sum of 472 is 4 + 7 + 2 = 13. Split off the last digit, and trust the call on the rest: the digit sum of 47.

    Code itAdd up the digits

    Write digit_sum(n), which returns the sum of the digits of a whole number n of 0 or more, using recursion: digit_sum(472) is 4 + 7 + 2 = 13.

    n % 10 is the last digit and n // 10 is the number without it: 472 % 10 is 2 and 472 // 10 is 47. Then press Watch it run to see the frames pile up and come back.

    ⌘+Enter runsPython starts when a code cell comes near or you run one
    Write your code where the starter says raise NotImplementedError, then press Run tests. Each check says what it expects.

    Back to Dana

    Now the opening question. Group the org chart's rows by manager, as module 3 grouped rows by a key, and you get a dict from each person to the list of their direct reports. Everyone gets an entry, with an empty list for people who manage nobody.

    The leap of faith works with any number of smaller calls. Trust count_under(r) to count everyone under each direct report r. Then each report adds 1 for themselves plus that count. Before you run it, count by hand: how many people work under Dana here?

    ⌘+Enter runs · edit freelyPython starts when a code cell comes near or you run one

    It prints 5: Ali, Bo, Cy, Eve and Fay. The base case hides inside the loop. Bo manages nobody, so the loop runs zero times and count_under("Bo") returns 0 without calling anything.

    The three checks hold. A person with no reports has nobody under them. Every call moves one level down the chart, and the chart has no loops, so the calls reach people who manage nobody. And if each smaller count is right, adding 1 plus that count for every report counts everyone under person. Now add "Gus" to Bo's list and a "Gus": [] entry, and run it again: it prints 6.

    This shape is a tree: a person at the top, and under each report, a smaller chart of the same kind. The next lesson walks binary trees the same way.

    When calls repeat

    factorial and digit_sum make one smaller call each, so their calls form a chain. count_under makes one per report. Some definitions need two smaller answers. The Fibonacci numbers start with F(0) = 0 and F(1) = 1, and each later one is the sum of the two before it: 0, 1, 1, 2, 3, 5, 8, 13. As code, the definition is the function:

    def fib(n):
        if n <= 1:                      # base cases: F(0) = 0 and F(1) = 1
            return n
        return fib(n - 1) + fib(n - 2)  # two smaller calls

    Now every call that is not a base case makes two calls. The figure draws fib(5) the same way as before. Before you press Next, guess how many calls it makes in all. (factorial(5) makes 5.)

    The tree repeats work, and the repeats get worse as n grows. Dana's chart never did this: each person has one manager, so count_under asks about each person once.

    Work it outHow many calls for fib(6)?

    Without a memo, how many calls does fib(6) make in all, counting every base case? Use the tree above: fib(6) is one call, plus every call that fib(5) makes, plus every call that fib(4) makes.

    calls

    Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.

    The n stepper shows the calls for n = 0 to 7: 1, 1, 3, 5, 9, 15, 25, 41. Each step up in n multiplies the calls by about 1.6, so the time is exponential: it grows by a fixed factor for every step up in n. It is usually quoted as O(2n), a looser upper bound. fib(30) makes 2,692,537 calls. Yet the stack is only n deep. Calls decide the time; depth decides the stack space.

    Write each answer down

    There are only n + 1 different questions, F(0) through F(n), but the tree asks them again and again. So write each answer down the first time it is worked out, and look it up after that. The notebook is a dict, memo, from k to F(k). Keeping a notebook of answers like this is called memoization; module 12 builds dynamic programming on it.

    Here is fib(5) with the memo on. The code under the tree checks the base case first, then the memo, and saves each new answer before returning it. Guess first: how many calls now?

    Each value from 2 to n is now worked out once, and any later request for it is one lookup: 9 calls for n = 5, against 15.

    One detail before the problem: where memo lives. In the figure's code it sits outside the function and outlives each call of fib. That is harmless here, since F(5) never changes, but in most problems the answers belong to one input, and leftover notes give wrong answers. So put memo = {} inside fib, and the recursion in a helper function defined inside fib. A function defined inside another can read the outer function's names and change the list or dict they point at, so the helper fills the outer memo, and every call of fib starts fresh.

    PredictA helper inside a function

    visit is defined inside countdown_list, so it can use the outer function's names. Type exactly what this prints.

    def countdown_list(n):
        seen = []
        def visit(k):
            seen.append(k)
            if k > 0:
                visit(k - 1)
        visit(n)
        return seen
    
    print(countdown_list(3))
    print(countdown_list(2))
    

    Now write it. The problem's speed test runs n = 40, which the plain recursion cannot finish in time.

    easyRecursionDynamic programming, 1D target 15 min

    Fibonacci number

    The Fibonacci numbers start with F(0) = 0 and F(1) = 1. Every later one is the sum of the two before it: F(k) = F(k - 1) + F(k - 2). So the sequence begins 0, 1, 1, 2, 3, 5, 8, 13.

    Write fib(n) that returns F(n) as an exact integer.

    Example 1
    Inputn = 6Output8

    F(0) through F(6) are 0, 1, 1, 2, 3, 5, 8.

    Example 2
    Inputn = 2Output1

    F(2) = F(1) + F(0) = 1 + 0 = 1.

    Example 3
    Inputn = 0Output0

    F(0) is a starting value, so there is nothing to add.

    Constraints
    • 0 ≤ n ≤ 90

    Plan it first

    Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

    ⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
    Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.

    Debrief. The definition written as code is the brute force: 25 calls for n = 6 (the first example), and 331,160,281 for n = 40. The memo cuts those to 11 and 79. The O(1) space follow-up is a loop up from F(0) and F(1) that keeps only the last two values, the first step into dynamic programming.

    Python can keep the memo for you. @cache from the functools module, written on the line above the def, saves every answer in a hidden dict; module 12 covers it. In this lab each level of a @cache function counts about twice against the depth limit, so it reaches about 2,500 levels, not 5,000.

    Halving the problem

    Back to power(x, n) from the shuffled lines: n + 1 calls, n + 1 deep. For n = 1,000 that is 1,001 nested calls, past plain Python's default limit. Shrinking the input by one is the slow way down. Halving it is fast.

    34 = 32 × 32: once you know 32 = 9, one multiplication gives 81. For an even n, xn is half * half, where half is x to the power n // 2. For an odd n, n // 2 rounds down, so the two halves fall one x short and need one more: 35 = 32 × 32 × 3. The leap of faith is the same as before; only the smaller input changes.

    Guess first: how many calls does power(3, 5) make, and what does the call with n = 2 return?

    Step through3 to the power 5 by halving
    Step 1 of 20
    Line 1 is about to run.
    def power(x, n):
    if n == 0:
    return 1
    half = power(x, n // 2)
    if n % 2 == 0:
    return half * half
    return half * half * x
    Names
    no names yet
    Output
    (nothing printed yet)

    Each call halves n, so there are about log₂ n calls. A reminder from module 2: log₂ n counts how many times you can halve n before reaching 1, so log₂ 8 is 3 (8, 4, 2, 1). For n = 1,000 the powers go 1,000, 500, 250, 125, 62, 31, 15, 7, 3, 1, 0: 11 calls instead of 1,001.

    Trace one by hand before the problem. Many rounds have no run button, and this is the skill that replaces it.

    On paperHalve 13 by hand

    On paper, trace power(2, 13) with the halving code from the trace above. Write the calls on the way down, then what each one returns on the way up, and count the multiplications. half * half * x is two multiplications; half * half is one.

    Work it on real paper: writing each step is the point. Then check your final answer here and compare your working with the walk-through.

    multiplications in all

    Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.

    The problem adds negative powers. x to the power −3 is 1 divided by x to the power 3, so 2.0 to the power −3 is 1 / 8 = 0.125. One check at the top handles a negative n, and the halving does the rest.

    mediumRecursionBits and math target 25 min

    Raise to a power

    Write my_pow(x, n) that returns x raised to the power n. Here x is a float and n is an integer that can be positive, zero or negative. A negative power means one over the positive power: 5.0 to the power -2 is 1 / 25 = 0.04. Any nonzero x to the power 0 is 1.0.

    Build the answer from multiplication and division. Do not use x ** n, pow or math.pow: the tests cannot stop you, but in an interview they skip the whole question.

    Example 1
    Inputx = 2.0, n = 10Output1024.0

    Ten 2s multiplied together.

    Example 2
    Inputx = 2.0, n = -3Output0.125

    One over the positive power: 1 / 23 = 1 / 8.

    Example 3
    Inputx = -2.0, n = 3Output-8.0

    An odd power of a negative number stays negative.

    Constraints
    • -100.0 < x < 100.0

    • -231 ≤ n ≤ 231 - 1

    • If x is 0, then n is positive.

    • The answer is between -104 and 104. Answers within 10-6 of the exact value are accepted.

    Plan it first

    Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

    ⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
    Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.

    Debrief. The solution is the traced function plus one check for a negative n. For n = 231 − 1 the stack is only 32 frames deep, where one x at a time takes over 2 billion multiplications. When a recursion goes one level per unit of n, ask whether it can halve.

    Last, say it out loud. The words you write here are the words you will use in the room.

    Say itSay it like you would in the room

    Explain to an interviewer, before typing, how you would compute x to the power n for a whole number n of 0 or more by halving. Cover the base case, the smaller call you trust and how you combine it, and the cost, including the stack.

    A few sentences first: 0 of 60 characters.

    Saved in this browser as you type.

    Next: Binary trees