Sub topic 11
Turning Tail Recursion into a Loop
This chapter assumes you can read Python functions and while loops. It also assumes you know what a tail call is from the previous chapter. CPython does not perform tail-call optimization, so a tail-recursive function still uses one stack frame per call and can raise RecursionError. Tail recursion keeps no pending work after the recursive call, and that is why it converts into a loop so easily.
The Mechanical Recipe
A tail-recursive function has three parts, and each one maps directly to a part of a loop:
| Recursive part | Loop equivalent |
|---|---|
| Parameters (`n`, `acc`) | Loop variables, initialized from the arguments |
| Base case test (`n == 0`) | Loop exit condition (loop `while not` base case) |
| Base case return value | Value returned after the loop ends |
| Tail call arguments (`n - 1`, `acc + n`) | Simultaneous reassignment of the loop variables |
Worked Example
Here is the accumulator version of summing 1..n, along with its loop form:
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)) # 5050Follow the recipe. The default acc=0 becomes acc = 0. The base case n == 0 becomes the exit condition while n != 0. The tail call sum_to_tail(n - 1, acc + n) becomes the two assignments. After the loop, return acc matches the base case's return. The loop version uses constant stack space, so sum_to_loop(1_000_000) works while sum_to_tail(1_000_000) raises RecursionError.
The Most Common Error: Update Order
In the recursive call, every argument is computed from the old values before any parameter changes. Sequential assignments in a loop do not behave that way. If you swap the two lines, the answer silently changes:
def sum_to_buggy(n):
acc = 0
while n != 0:
n = n - 1
acc = acc + n # uses the new n, not the old one
return acc
print(sum_to_buggy(100)) # 4950, not 5050Python's tuple assignment computes every right-hand side first and then binds the names. That matches the semantics of a function call exactly:
def sum_to_safe(n):
acc = 0
while n != 0:
n, acc = n - 1, acc + n
return acc
print(sum_to_safe(100)) # 5050Other Pitfalls
- Not actually tail recursive.
return n * f(n - 1)still has a multiplication pending after the call returns. Rewrite it with an accumulator first, then convert. If the function makes several recursive calls, as tree traversals do, it needs an explicit stack, which the next chapter covers. - Inverted exit condition. The loop runs while the base case is false. If the function has several base cases, combine them:
while not (a or b). - Multiple tail calls in branches. Each branch becomes its own reassignment inside an
if/elsein the loop body.
Exercise
Convert this tail-recursive function into a loop: def gcd(a, b): if b == 0: return a; return gcd(b, a % b)
Show answer
def gcd(a, b): while b != 0: a, b = b, a % b; return a. The parameters a and b become the loop variables, the base case b == 0 becomes the exit condition, and the tail call's arguments become the tuple assignment. A tuple assignment is required here, because writing a = b on its own first would lose the old a needed for a % b.
Exercise
Why does sumtobuggy return 4950 for n = 100?
Show answer
It decrements n before adding it, so each iteration adds n - 1 instead of n. The values added are 99, 98, ..., 0, which sum to 4950.