Code Explanation:
1) from functools import lru_cache
Imports the lru_cache decorator from the functools module.
lru_cache provides a simple way to memoize function results (cache return values keyed by the function arguments).
2) @lru_cache(maxsize=None)
Applies the decorator to the function f.
maxsize=None means the cache is unbounded (no eviction) — every distinct call is stored forever (until program exit or manual clear).
After this, f is replaced by a wrapper that checks the cache before calling the original function.
3) def f(x):
Defines the (original) function that we want to cache. Important: the wrapper produced by lru_cache controls calling this body.
print("calc", x)
return x * 2
On a cache miss (first time f(3) is called), the wrapper calls this body:
It prints the side-effect calc 3.
It returns x * 2 → 6.
On a cache hit (subsequent calls with the same argument), the wrapper does not execute this body, so the print("calc", x) side-effect will not run again — the cached return value is used instead.
4) print(f(3)) (first call)
The wrapper checks the cache for key (3). Not found → cache miss.
Calls the original f(3):
Prints: calc 3
Returns 6
print(...) then prints the returned value: 6
So the console so far:
calc 3
6
5) print(f(3)) (second call)
The wrapper checks the cache for key (3). Found → cache hit.
It returns the cached value 6 without executing the function body (so no calc 3 is printed this time).
print(...) prints 6.
Final console output (exact order and lines):
calc 3
6
6
✅ Final Output
calc 3
6
6
Download Book - 500 Days Python Coding Challenges with Explanation


0 Comments:
Post a Comment