Code Explanation:
1) from functools import lru_cache
Imports the lru_cache decorator from Python’s functools module.
lru_cache (Least Recently Used cache) is used to memoize function results:
If a function is called with the same arguments again, it returns the cached result instead of recalculating.
2) @lru_cache(maxsize=None)
Decorates the function square.
maxsize=None means:
There’s no limit on how many results can be cached.
All calls with unique arguments are remembered.
3) def square(x):
Defines the function square that takes an argument x.
4) print("calc", x)
This line prints "calc", x every time the function actually computes something.
If the result is returned from cache, this line will not run.
5) return x * x
Computes the square of x and returns it.
6) print(square(3))
First call:
Since 3 is not in the cache, square(3) runs fully.
Prints "calc 3".
Returns 9.
So print(...) prints 9.
7) print(square(3))
Second call:
Now 3 is already cached.
The function body does not execute again (no "calc 3" this time).
Cached value 9 is returned instantly.
print(...) prints 9.
Final Output
calc 3
9
9
Download Book - 500 Days Python Coding Challenges with Explanation
.png)

0 Comments:
Post a Comment