Do the work once.
Recognise overlapping subproblems and avoid recomputing the same answer.
01 The idea
Dynamic programming saves results of overlapping subproblems. Top-down memoization adds a cache to a recursive solution; bottom-up tabulation fills results in an order where dependencies are already available. The technique requires a well-defined state and a recurrence. Caching arbitrary code is not automatically correct, especially when results depend on changing external data.
02 The experiment
Read it once. Predict what will happen. Then copy it into a .py file and run it in your local Python setup.
from functools import lru_cache
@lru_cache(maxsize=None)
def ways(steps):
if steps < 0: return 0
if steps == 0: return 1
return ways(steps - 1) + ways(steps - 2)
print(ways(5))
print(ways.cache_info().currsize)8 7
03 Under the hood
- 1
ways(n) counts routes using one- or two-step moves. The two base cases define a valid empty route and impossible negative routes.
- 2
Without caching, many calls repeat. The cache stores each distinct integer state, reducing the number of evaluated states to linear growth here.
- 3
A bottom-up version can keep only the two most recent values, using constant auxiliary storage. Choose a state that captures everything the answer depends on, and account for potentially large integer arithmetic in detailed performance analysis.
04 Your turn, builder
Implement the same count bottom-up with two running values.
Reveal one possible solution +
def ways(steps):
if steps < 0: return 0
previous, current = 1, 1
for _ in range(steps):
previous, current = current, previous + current
return previous
print(ways(5))05 Check your signal
What makes memoization useful here?
Experiment. Logged.
When you can explain the idea and make the example your own, mark it complete. Your log stays in this browser.
Keep exploring
Go deeper with the official Python guide ↗.