Code Explanation:
1. Function Definition with Memoization
def foo(n, cache={0: 1}):
Defines a function foo that calculates factorial of a number n.
cache is a default dictionary used to store already computed values (memoization).
Initially, it contains {0: 1} because 0! = 1.
2. Check if Result Already Cached
if n not in cache:
Checks if n's factorial is already computed and saved in the cache.
If not, we need to compute it.
3. Recursive Calculation and Caching
cache[n] = n * foo(n - 1)
If n is not in the cache:
Recursively call foo(n - 1) to get (n - 1)!
Multiply it by n to compute n!
Save it to cache[n] so it's not recomputed in the future.
4. Return Cached Result
return cache[n]
Whether it was just computed or already existed, return cache[n].
5. Call and Print: foo(3)
print(foo(3))
What Happens:
3 not in cache
→ compute 3 * foo(2)
2 not in cache
→ compute 2 * foo(1)
1 not in cache
→ compute 1 * foo(0)
0 is in cache → 1
foo(1) = 1 * 1 = 1 → store in cache
foo(2) = 2 * 1 = 2 → store in cache
foo(3) = 3 * 2 = 6 → store in cache
Printed Output:
6
6. Call and Print: foo(2)
print(foo(2))
What Happens:
2 is already in cache from previous call.
Just return cache[2] = 2.
Printed Output:
2
Final Output
6
2
.png)

0 Comments:
Post a Comment