Code Explanation:
1. Importing lru_cache
from functools import lru_cache
functools is a Python module with higher-order functions and decorators.
lru_cache = Least Recently Used cache.
It stores results of function calls so repeated inputs don’t need recalculation.
2. Applying the Decorator
@lru_cache(maxsize=None)
This tells Python to cache all results of the function that follows.
maxsize=None → the cache can grow indefinitely.
Whenever the function is called with the same argument, the result is retrieved from memory instead of being computed again.
3. Defining the Fibonacci Function
def fib(n):
if n < 2:
return n
return fib(n-1) + fib(n-2)
Step-by-step:
Base case:
If n < 2 (i.e., n == 0 or n == 1), return n.
fib(0) = 0
fib(1) = 1
Recursive case:
Otherwise, return the sum of the two previous Fibonacci numbers:
fib(n) = fib(n-1) + fib(n-2)
4. Calling the Function
print(fib(10))
Starts the recursive calculation for fib(10).
Uses the formula repeatedly until it reaches the base cases (fib(0) and fib(1)).
Thanks to lru_cache, each intermediate result (fib(2) … fib(9)) is computed once and reused.
5. Fibonacci Sequence (0 → 10)
fib(0) = 0
fib(1) = 1
fib(2) = 1
fib(3) = 2
fib(4) = 3
fib(5) = 5
fib(6) = 8
fib(7) = 13
fib(8) = 21
fib(9) = 34
fib(10) = 55
Final Output
55
.png)

0 Comments:
Post a Comment