🧮Memoization
Also known as Memoize, Memoisation, functools.cache
Saving a function's answer for each input. The same call is then instant.
Think of it like
Think of it like a note on the fridge. It holds an answer you already worked out.
Example
Lucy adds @functools.cache to her Fibonacci function. fib(50) comes back at once instead of running for hours.
Why it matters
One line can turn a function that never finishes into one that answers at once.
Definition
Example code
python
import functools
@functools.cache
def fib(n):
return n if n < 2 else fib(n - 1) + fib(n - 2)
print(fib(50)) # 12586269025Common mistake
Key takeaways
- 1Save each answer. Keyed by its input.
- 2Pure functions only. Same input, same answer.
- 3Top-down DP. One kind of dynamic programming.