
Cache the Bridge Routes
Some functions get called again and again with the same arguments.
Recursion is the classic case. functools.lru_cache remembers results,
so each unique call is computed only once:
from functools import lru_cache
@lru_cache(maxsize=None) # or simply @cache
def fib(n):
return n if n < 2 else fib(n - 1) + fib(n - 2)
fib(100) # instant, instead of trillions of calls
fib.cache_info() # CacheInfo(hits=98, misses=101, ...)
maxsize=128keeps only the 128 most recently used results (LRU = least recently used gets dropped).maxsize=Nonekeeps everything.- Arguments must be hashable (numbers, strings, tuples, but not lists).
- Only cache pure functions, whose result depends only on the arguments.
Assignment
A bridge has steps planks, and you may cross 1, 2 or 3 planks at a
time. bridge_routes(steps) counts the possible routes. Without a cache,
bridge_routes(50) would take hours!
Fill in the three blanks ___ to import lru_cache, decorate the
function with maxsize=None, and call the cache statistics method.
A bridge has steps planks, and you may cross 1, 2 or 3 planks at a
time. bridge_routes(steps) counts the possible routes. Without a cache,
bridge_routes(50) would take hours!
Fill in the three blanks ___ to import lru_cache, decorate the
function with maxsize=None, and call the cache statistics method.
Press Run to try your code, then Check to test it.