Memoizing previous results with lru_cache
The
lru_cache
decorator transforms a given function into a function that might perform more quickly. The
LRU means Least Recently Used: a finite pool of recently used items is retained. Items not frequently used are discarded to keep the pool to a bounded size.
Since this is a decorator, we can apply it to any function that might benefit from caching previous results. We might use it as follows:
from functools import lru_cache @lru_cache(128) def fibc(n): """Fibonacci numbers with naive recursion and caching >>> fibc(20) 6765 >>> fibc(1) 1 """ if n == 0: return 0 if n == 1: return 1 return fibc(n-1) + fibc(n-2)
This is an example based on Chapter 6, Recursions and Reductions. We've applied the ...
Get Functional Python Programming now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.