Memoization
Cache expensive function results with a memoization decorator. Python provides functools.lru_cache out of the box.
Cache expensive function results with a memoization decorator. Python provides functools.lru_cache out of the box.
from functools import lru_cache
@lru_cache(maxsize=128)
def fibonacci(n):
if n < 2:
return n
return fibonacci(n-1) + fibonacci(n-2)
print(fibonacci(50)) # instant, no recursion explosion
Use @functools.cache (Python 3.9+) for an unbounded cache with simpler syntax.