Intermediate LevelPython
How does @functools.lru_cache(maxsize=128) optimize recursive functions via Least Recently Used memoization?
❓ Interview Prompt: Explain `@functools.lru_cache`, Least Recently Used (LRU) cache eviction, memoizing pure functions, and `cache_info()`.
'@functools.lru_cache(maxsize=128)' caches function call return values in a dictionary keyed by arguments:
Time Complexity Transformation:
Memoizing pure recursive functions (like Fibonacci) drops execution time complexity from exponential $O(2^N)$ down to linear $O(N)$ instantly by eliminating duplicate sub-tree calculations!
Code Implementation Example
python
import functools
@functools.lru_cache(maxsize=None) # Unlimited cache
def fibonacci(n):
if n < 2:
return n
return fibonacci(n - 1) + fibonacci(n - 2)
print(fibonacci(100)) # Computes instantly in O(N) time!
print(fibonacci.cache_info()) # Hits, misses, maxsize💡Optimizing recursive Fibonacci calculations using @lru_cache.
🎯 Interview Key Takeaway
Use @functools.lru_cache to memoize pure functions and eliminate redundant computations.
#lru_cache#functools#Memoization#Optimization#Intermediate
Back to all Python Questions→