Sub topic 10
Bottom-Up Fibonacci with a Loop
This chapter assumes you can read Python loops and tuple assignment. It also assumes you know the naive recursive fib and the memoized fib_memo from the previous chapters, along with Big-O notation.
Memoization starts at n and recurses down, caching results on the way back up. Bottom-up iteration reverses the direction. It starts from the base cases, fib(0) = 0 and fib(1) = 1, and builds upward until it reaches n. No call ever has to wait for a smaller subproblem, because every smaller value already exists when it is needed.
Filling a Table from the Bottom
The most direct bottom-up version stores every Fibonacci number in a list. Index i holds fib(i).
def fib_table(n):
if n < 2:
return n
table = [0] * (n + 1)
table[1] = 1
for i in range(2, n + 1):
table[i] = table[i - 1] + table[i - 2]
return table[n]
print(fib_table(10)) # 55The loop body runs n - 1 times and does a constant amount of work each time, so the running time is O(n). The list holds n + 1 entries, so the extra space is also O(n). This matches the memoized version, with no recursion involved.
Keeping Only Two Values
Look at the loop body again. Computing table[i] reads only table[i - 1] and table[i - 2]. Every older entry is dead weight, so you can replace the whole list with two variables.
def fib_iter(n):
a, b = 0, 1
for _ in range(n):
a, b = b, a + b
return a
print(fib_iter(10)) # 55Before each pass through the loop, a holds fib(k) and b holds fib(k + 1), where k is the number of passes completed so far. One pass shifts the pair forward by one position. After n passes, a holds fib(n).
Here is the trace for fib_iter(5):
| Passes done | a | b |
|---|---|---|
| 0 | 0 | 1 |
| 1 | 1 | 1 |
| 2 | 1 | 2 |
| 3 | 2 | 3 |
| 4 | 3 | 5 |
| 5 | 5 | 8 |
The function returns a = 5, which is fib(5).
Comparing the Three Approaches
| Version | Time | Extra space | Recursion depth |
|---|---|---|---|
| `fib` (naive) | O(φⁿ), exponential | O(n) stack | n |
| `fib_memo` | O(n) | O(n) cache + stack | n |
| `fib_iter` | O(n) | O(1) | none |
Since fib_iter makes no recursive calls, it never reaches Python's recursion limit. fib_iter(100000) runs without trouble. fib_memo(100000) called on a cold cache raises RecursionError.
Common Errors
The most frequent bug is splitting the simultaneous update into two statements:
def fib_broken(n):
a, b = 0, 1
for _ in range(n):
a = b
b = a + b # a was already overwritten
return a
print(fib_broken(5)) # 8, not 5When the second line runs, a already holds the new value. That makes b double on every pass, giving 1, 2, 4, 8 instead of the Fibonacci numbers. Python's tuple assignment evaluates the whole right-hand side before it assigns anything, and that is why a, b = b, a + b works.
Exercise
What does fib_iter(0) return, and why does the loop body not run?
Show answer
It returns 0. range(0) is empty, so the loop never executes, and a keeps its initial value 0, which equals fib(0).
Exercise
Write a bottom-up function for the sequence T(0)=0, T(1)=0, T(2)=1, T(n)=T(n-1)+T(n-2)+T(n-3) that uses O(1) extra space.
Show answer
def trib(n): a, b, c = 0, 0, 1 for _ in range(n): a, b, c = b, c, a + b + c return a The loop keeps three values because each term depends on the three before it. For example, trib(4) returns 2.