Step-by-Step Execution:
1. Import lru_cache from functools
lru_cache (Least Recently Used Cache) is a built-in Python decorator that caches function calls to optimize performance.
It stores previously computed values, avoiding redundant calculations.
2. Define the Fibonacci Function with Caching
@lru_cache(maxsize=2)
def fib(n):
return n if n <= 1 else fib(n-1) + fib(n-2)
@lru_cache(maxsize=2): Caches the two most recently used function calls.
Base case: fib(0) = 0, fib(1) = 1
Recursive case: fib(n) = fib(n-1) + fib(n-2)
3. Compute fib(10)
print(fib(10))
The function computes fib(10) using recursion and caches recent calls.
Since maxsize=2, only the last two computed results remain cached.
4. Print Cache Information
print(fib.cache_info())
This outputs:
CacheInfo(hits=X, misses=Y, maxsize=2, currsize=2)
hits: How many times a cached value was used.
misses: How many times a new value was computed.
maxsize: Maximum cache size (2 in this case).
currsize: Current number of cached values (2).
Final Output:
Cache only keeps last 2 calls
0 Comments:
Post a Comment