Code Explanation:
1. Importing Required Module
from functools import lru_cache
Imports the lru_cache decorator from Python's functools module.
Used to cache function results for faster access on repeated calls.
Follows a Least Recently Used (LRU) eviction strategy when the cache exceeds the set size.
2. Initializing the List
calls = []
Creates an empty list calls.
This will store every actual computation input (i.e., uncached calls to f(x)).
3. Defining a Cached Function
@lru_cache(maxsize=2)
def f(x):
calls.append(x)
return x * x
Defines a function f(x) that:
Appends x to the calls list.
Returns x² (square of x).
The function is decorated with @lru_cache(maxsize=2):
This means only the two most recently used unique inputs are stored.
If a new input is added beyond that, the least recently used is evicted from cache.
4. Making Function Calls
f(2)
- Not in cache → computed.
- `calls = [2]`
- Cache: `{2: 4}`
f(3)
Not in cache → computed.
calls = [2, 3]
Cache: {2: 4, 3: 9}
f(2)
- **In cache** → result reused.
- No change to `calls`.
- Cache still: `{2: 4, 3: 9}`
f(4)
Not in cache → computed.
Cache full → evicts least recently used, which is 3.
calls = [2, 3, 4]
Cache: {2: 4, 4: 16}
f(3)
- Not in cache (was evicted earlier) → computed again.
- Evicts `2` (now least recently used).
- `calls = [2, 3, 4, 3]`
- Cache: `{4: 16, 3: 9}`
5. Printing the Result
print(calls)
Output:
[2, 3, 4, 3]
These are the actual inputs for which the function was executed (not cached).
Final Output:
[2, 3, 4, 3]
.png)

0 Comments:
Post a Comment