Sub topic 2
Tail Recursion and Accumulator Parameters
This chapter assumes you can read Python functions, know Big-O notation, and have seen the recursive factorial from the previous chapter.
Tail Recursion and Accumulators
A call is a tail call when it is the last thing a function does, so nothing is left to compute after it returns. In plain factorial, the multiplication n * factorial(n - 1) still has to happen after the inner call returns, so that call is not a tail call. An accumulator is an extra parameter that carries the partial result down the chain of calls, which moves the multiplication before the call:
def factorial_acc(n, acc=1):
if n == 0:
return acc
return factorial_acc(n - 1, acc * n)
print(factorial_acc(5)) # 120Recursion Trees
A recursion tree draws each call as a node, with its recursive calls as children. If you count the nodes, you get the number of calls. If you multiply that count by the work done in each call, you get the running time. Factorial's tree is a single chain of n + 1 nodes. Fibonacci's tree branches at every call.
Fibonacci and Repeated Work
def fib(n):
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
print(fib(10)) # 55fib(2) is computed twice in this tree. The call count follows C(n) = C(n−1) + C(n−2) + 1, which grows like Fibonacci itself, about 1.618ⁿ. So naive fib runs in exponential time.
Memoization
Memoization caches each result the first time it is computed. Every later call with the same argument returns the cached value immediately.
from functools import lru_cache
@lru_cache(maxsize=None)
def fib_memo(n):
if n < 2:
return n
return fib_memo(n - 1) + fib_memo(n - 2)
print(fib_memo(80)) # 23416728348467685Each value from 0 to n is computed once, which takes O(n) time and O(n) memory. The recursion depth is still about n, so fib_memo(5000) called cold can hit the recursion limit.
| Version | Time | Extra space |
|---|---|---|
| `fib` | O(1.618ⁿ) | O(n) stack |
| `fib_memo` | O(n) | O(n) cache + stack |
Exercise
How many calls does naive fib(5) make in total, counting the first call?
Show answer
15. Using C(n) = C(n−1) + C(n−2) + 1 with C(0) = C(1) = 1 gives C(2) = 3, C(3) = 5, C(4) = 9, and C(5) = 15.
Exercise
Is return fib(n - 1) + fib(n - 2) a tail call? Why or why not?
Show answer
No. The addition still runs after both calls return, so neither call is the last operation in the function.