Python dynamic programming
Reuse earlier results instead of recomputing overlapping subproblems.
def fibonacci(n):
if n < 0:
raise ValueError("n must be nonnegative")
a, b = 0, 1
for _ in range(n):
a, b = b, a + b
return a
print(fibonacci(6))
assert fibonacci(0) == 0
assert fibonacci(1) == 18
Explanation
Fibonacci numbers satisfy F(0)=0, F(1)=1, and F(n)=F(n-1)+F(n-2). Naive recursion repeats the same subproblems many times.
A bottom-up solution keeps only the two most recent values because the recurrence does not need older entries. The simultaneous assignment evaluates both right-hand values before rebinding either name.
Explore the dry run
def fibonacci(n): if n < 0: raise ValueError("n must be nonnegative") a, b = 0, 1 for _ in range(n): a, b = b, a + b return a print(fibonacci(6))assert fibonacci(0) == 0assert fibonacci(1) == 1Follow the example
Start to inspect the source, values, and output. These prepared steps explain the published sample; grouped loop steps describe multiple iterations.
View the complete dry-run table
| Step / line | What happens | State after step | Output so far |
|---|---|---|---|
| Initialize F(0) and F(1). | a = 0, b = 1 | — | |
| First iteration. | a = 1, b = 1 | — | |
| Second iteration. | a = 1, b = 2 | — | |
| Third iteration. | a = 2, b = 3 | — | |
| Fourth iteration. | a = 3, b = 5 | — | |
| Fifth iteration. | a = 5, b = 8 | — | |
| Sixth iteration. | a = 8, b = 13 | — | |
| Return a, which now holds F(6). | a = 8 | 8 |
Cost and common mistakes
O(n) additions and O(1) integer variables; the integers grow with n, so bit-level time and space are not constant.
- The input contract is a nonnegative integer.
- Using sequential assignments a=b then b=a+b changes the recurrence.
Try it yourself
Predict fibonacci(7) and fibonacci(8).
Reveal answer and reasoning
They are 13 and 21. Each uses the sum of the previous two results.