Sub topic 3
Tail Calls and Tail-Call Optimization
This chapter assumes you can read recursive functions, know what a stack frame is, and can read simple Big-O notation.
Tail Calls and Tail-Call Optimization
A tail call is a call that is the last thing a function does before it returns. Nothing is left to do with its result. In some languages, such as Scheme, the runtime can reuse the current frame for a tail call. This is called tail-call optimization (TCO), and it keeps stack depth constant. CPython does not perform TCO, so every tail call still adds a frame.
Turning Tail Recursion into a Loop
A tail-recursive function carries its partial result in an accumulator parameter. To convert it, turn each parameter into a loop variable. The base case becomes the loop's exit condition.
def sum_to_tail(n, acc=0):
if n == 0:
return acc
return sum_to_tail(n - 1, acc + n)
def sum_to_loop(n):
acc = 0
while n != 0:
acc = acc + n
n = n - 1
return acc
print(sum_to_tail(100)) # 5050
print(sum_to_loop(100)) # 5050Simulating Recursion with an Explicit Stack
Non-tail recursion still has pending work after the call, so a plain loop cannot replace it. Instead, you manage a list as your own stack. Push the right child before the left so that the left child is popped first.
def preorder_iterative(root):
out = []
stack = [root] if root is not None else []
while stack:
node = stack.pop()
out.append(node.value)
if node.right is not None:
stack.append(node.right)
if node.left is not None:
stack.append(node.left)
return outMemoization and Bottom-Up Iteration
Naive fib(n) recomputes the same subproblems and takes exponential time. Memoization caches results, which brings the cost down to O(n) time but still uses O(n) stack depth. A bottom-up loop runs in O(n) time with O(1) extra space.
def fib_bottom_up(n):
a, b = 0, 1
for _ in range(n):
a, b = b, a + b
return a
print(fib_bottom_up(80)) # 23416728348467685Mutual Recursion
Mutual recursion means functions call each other, as when is_even(n) calls is_odd(n - 1). Every one of those calls still pushes a frame onto the same stack, so depth limits apply just as they do to ordinary recursion.
Choosing the Right Approach
| Situation | Prefer |
|---|---|
| Tree-shaped data, shallow depth | Recursion |
| Deep or input-sized depth in Python | Loop or explicit stack |
| Overlapping subproblems | Memoization or bottom-up |
| Language with guaranteed TCO | Tail recursion is safe |
Exercise
Convert def count(n, acc=0): return acc if n == 0 else count(n - 1, acc + 1) into a while loop.
Show answer
def count(n): acc = 0 then while n != 0: acc += 1; n -= 1 and finally return acc. The parameters become loop variables, and the base case becomes the loop's exit condition.