Code Explanation:
1️⃣ Importing lru_cache
from functools import lru_cache
Explanation
Imports lru_cache from the functools module.
It is used for memoization (caching function results).
2️⃣ Applying Decorator
@lru_cache(None)
Explanation
This decorator caches results of function calls.
None means unlimited cache size.
๐ So once a value is computed, it is stored and reused.
3️⃣ Defining Function
def f(n):
Explanation
Defines function f that takes input n.
4️⃣ Base Condition
if n <= 1:
return n
Explanation
If n is 0 or 1, return n.
This is the base case of recursion.
5️⃣ Recursive Case
return f(n-1) + f(n-2)
Explanation
This is Fibonacci logic.
Computes:
f(n) = f(n-1) + f(n-2)
6️⃣ Calling Function
print(f(5))
Explanation
Calls f(5).
๐ Execution (Step-by-Step)
Without cache:
f(5)
= f(4) + f(3)
= (f(3)+f(2)) + (f(2)+f(1))
= ...
๐ Many repeated calls!
⚡ With lru_cache
Each value is computed once only:
Call Value
f(0) 0
f(1) 1
f(2) 1
f(3) 2
f(4) 3
f(5) 5
๐ค Final Output
5

0 Comments:
Post a Comment