Python 3D Academyবাংলা

Recursion again: the call stack, frame by frame

🌍 In real life. A set of nesting dolls sits on a shelf at the village fair. How many dolls are there? Open the biggest one, and inside is the same puzzle, only smaller: another set of dolls. Keep opening until a doll is solid, with nothing inside. Then close them back up: the last doll you opened is the first one you close.

Chapter 17 met recursion. This lesson looks at it the way an algorithm designer does: three questions that write any recursion, the call stack that runs it (a stack, as in Chapter 39), what it costs in time and memory, and how to do the stack's job yourself when recursion would go too deep.

The idea in one sentence: a recursive function solves a problem by calling itself on a smaller version of the same problem, and Python keeps one frame per unfinished call on the call stack until each call gets its answer.

Its words:

  • base case: the smallest problem, answered straight away with no further call (the solid doll)
  • recursive case: make the problem smaller, call yourself on it, then build your answer from the smaller answer
  • frame: one call's own box of local variables, separate from every other call's
  • depth: how many frames are on the stack at once

Three questions write any recursion:

  1. What is the smallest problem, and its answer? (the base case)
  2. How do I make my problem smaller? (the recursive call)
  3. If the smaller call gives me the right answer, how do I build mine from it? (combining)

Here d is a row of dolls written as brackets: '((()))' is three dolls, one inside the next. d[1:-1] takes the outer doll off. Watch the frames pile up while dolls are opened, and come off in reverse order:

Why it is correct. It is the same argument every time, like climbing a ladder:

  • the base case is right: an empty row has 0 dolls
  • if the smaller call is right, the combine is right: one doll plus the dolls inside it
  • every call is smaller than the one before (two brackets fewer), so the calls must reach the base case

So you never need to follow all the calls in your head: trust the smaller call, check those three things, and the whole recursion is right.

What it costs.

  • Time: add up the work of every call. dolls on k dolls makes k + 1 calls. Each d[1:-1] copies the string, so the work per call is not constant: passing an index instead of a slice saves that copying.
  • Memory: every frame on the stack takes memory until its call returns, so the memory is the depth. Going one step smaller each time on n items means n frames at once: O(n) memory, even when the answer is one number.
  • The limit: Python allows about 1000 frames. A recursion that shrinks by one on a list of 5000 items stops with RecursionError. Halving (Lesson 42.3) or a loop does not.

Where recursion shines: things inside things. A list can hold lists, which hold lists, like dolls in dolls or folders in folders. There is no fixed number of loops that walks it, but the three questions do: a plain value is the base case, and a list inside is a smaller problem of the same kind.

Doing the stack's job yourself. Every recursion can be turned into a loop with your own stack (a list, as in Chapter 39). Push the work still to do, pop the most recent, and push what it contains, in reverse so the first item comes off first. Your list can grow as deep as memory allows: no 1000-frame limit.

def flatten(items):
    out = []
    for x in items:
        if isinstance(x, list):
            out.extend(flatten(x))   # a smaller problem: trust it
        else:
            out.append(x)            # a plain value: the base case
    return out

def flatten_stack(items):
    out = []
    stack = [items]
    while stack:
        x = stack.pop()
        if isinstance(x, list):
            stack.extend(reversed(x))  # the first item comes off first
        else:
            out.append(x)
    return out

box = [1, [2, [3, [4]]], 5]
print(flatten(box))
print(flatten_stack(box))

import sys

def total(nums):                 # one call per item: n frames
    return 0 if not nums else nums[0] + total(nums[1:])

print(total([4, 5, 6]))
print(sys.getrecursionlimit())   # about 1000: total() of a longer list fails
print(sum(range(1500)))          # a loop has no such limit

Mistakes and edge cases.

  • no base case, or a call that isn't smaller: the frames pile up until RecursionError. Check question 2: is the argument really closer to the base case?
  • a branch that forgets to return: the caller gets None, and 1 + None raises TypeError
  • an empty list: flatten([]) should be [], and the loop handles it with no special case
  • deep input: shrinking by one on long or very nested data hits the 1000-frame limit; use a loop and your own stack

Quiz

  1. What does this print?

    def dolls(n):
        print(n, end=" ")
        if n > 1:
            dolls(n - 1)
        print(-n, end=" ")
    
    dolls(3)
  2. While dolls(3) above runs, what is the most frames of dolls on the call stack at once?

    • 3
    • 1
    • 6
  3. total([4, 5, 6]) never finishes: it stops with a RecursionError. Which line is wrong?

    def total(nums):
        if nums == []:
            return 0
        return nums[0] + total(nums)
  4. A recursion goes one item smaller each time on a list of n items and returns one number. How much memory does it need?

    • O(n): n frames are on the stack at the deepest point
    • O(1): it only returns one number
    • O(log n)
  5. Why does a recursive sum that goes one item at a time fail on a list of 5000 numbers?

    • It needs about 5000 frames, but Python allows about 1000 (RecursionError)
    • Adding 5000 numbers is too slow for Python
    • Lists longer than 1000 can't be sliced

Coding tasks

  1. Write a recursive flatten(items): all the plain values in a list that may hold lists (which may hold lists…), in order. flatten([1, [2, [3]], 4]) is [1, 2, 3, 4].

  2. Write a recursive deepest(items): how deep the lists nest. A list with no lists inside has depth 1, and each list inside a list adds 1. deepest([1, [2, [3]]]) is 3, and deepest([]) is 1.

  3. Write flatten_stack(items): the same answer as flatten, but without recursion (it must not call itself): keep your own stack in a list, so no nesting is too deep for it.