Code Explanation:
1. Importing the LRU Cache Decorator
from functools import lru_cache
functools is a standard Python module that provides tools for functional programming.
lru_cache is a decorator for memoization – it caches the results of expensive function calls so they don’t need to be recomputed.
LRU stands for Least Recently Used, which is a cache strategy.
2. Decorating the Fibonacci Function with @lru_cache
@lru_cache(maxsize=None)
This decorator wraps the fib() function to automatically cache its return values.
maxsize=None means the cache can grow without limit – all results will be stored.
So if you call fib(5) once, its value is stored. Next time, it returns the cached result instantly.
3. Defining the Recursive Fibonacci Function
def fib(n):
Defines a function fib to compute the n-th Fibonacci number.
Takes one parameter n (an integer).
4. Handling the Base Cases
if n < 2:
return n
The base case of the Fibonacci sequence:
fib(0) returns 0
fib(1) returns 1
For n < 2, the function just returns n.
5. Recursive Case for Fibonacci
return fib(n-1) + fib(n-2)
If n >= 2, compute recursively using:
fib(n) = fib(n-1) + fib(n-2)
This mirrors the Fibonacci sequence:
fib(2) = fib(1) + fib(0) = 1 + 0 = 1
And so on...
Thanks to @lru_cache, repeated calls to fib(n-1) or fib(n-2) are fast after the first computation.
6. Calling the Function and Printing the Result
print(fib(10))
Calls the fib() function with n = 10.
Computes the 10th Fibonacci number.
Output will be:
55


0 Comments:
Post a Comment