Code Explanation:
1. Importing the lru_cache Decorator
from functools import lru_cache
lru_cache is a decorator from Python's functools module.
It stands for Least Recently Used cache.
It automatically stores the results of expensive function calls and reuses them when the same inputs occur again.
2. Using the @lru_cache Decorator
@lru_cache(maxsize=None)
This line decorates the fib function.
maxsize=None means the cache can grow without limit.
It helps speed up recursive functions like Fibonacci by memoizing results.
3. Defining the Recursive Fibonacci Function
def fib(n):
if n < 2: return n
return fib(n-1) + fib(n-2)
Base Case: If n is 0 or 1, return n.
Recursive Case: Return the sum of the two previous Fibonacci numbers:
fib(n-1) and fib(n-2).
4. Calling the Function and Printing Result
print(fib(5))
Calls the fib function with argument 5.
The function computes the 5th Fibonacci number:
fib(5) = fib(4) + fib(3)
= (fib(3) + fib(2)) + (fib(2) + fib(1))
= ...
= 5
Result is 5, which is printed.
Final Output:
5
0 Comments:
Post a Comment