Code Explanation:
1. Importing lru_cache from functools
from functools import lru_cache
lru_cache stands for Least Recently Used Cache.
It’s a decorator that remembers the results of function calls, so if the same inputs occur again, it returns the cached result instead of recomputing.
2. Defining the Recursive Fibonacci Function with Caching
@lru_cache(maxsize=2)
def fib(n):
return 1 if n < 2 else fib(n-1) + fib(n-2)
Key Points:
This defines a recursive Fibonacci function.
Base case:
fib(0) = 1
fib(1) = 1
Recursive case:
fib(n) = fib(n-1) + fib(n-2)
Decorated with @lru_cache(maxsize=2):
The cache will store only the last two most recently used results.
When a new call is added and the cache is full, the least recently used entry is removed.
3. Calling the Function
=print(fib(5))
What Happens Internally:
Let’s simulate the recursive calls with caching (maxsize=2):
fib(5)
= fib(4) + fib(3)
= (fib(3) + fib(2)) + (fib(2) + fib(1))
= ((fib(2) + fib(1)) + (fib(1) + fib(0))) + ((fib(1) + fib(0)) + 1)
But due to the limited cache (maxsize=2), the cache will only retain the two most recently used values during execution. This means:
Many results will be evicted before they can be reused.
You don’t get the full performance benefit that you would with a larger cache or unlimited size.
Result:
The output is still 8 (correct Fibonacci result for fib(5)), but with less efficiency due to constant cache eviction.
Why Use maxsize=2?
This small size shows how limited cache can impact performance — useful for experimentation or memory-constrained scenarios.
You'd typically use a larger maxsize (or None for unlimited) in real-world performance-sensitive recursive computations.
Final Output:
8
.png)

0 Comments:
Post a Comment