Sunday, 15 June 2025

Python Coding challenge - Day 551| What is the output of the following Python Code?

 


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]

Download Book - 500 Days Python Coding Challenges with Explanation

0 Comments:

Post a Comment

Popular Posts

Categories

100 Python Programs for Beginner (118) AI (161) Android (25) AngularJS (1) Api (6) Assembly Language (2) aws (27) Azure (8) BI (10) Books (254) Bootcamp (1) C (78) C# (12) C++ (83) Course (84) Coursera (299) Cybersecurity (28) Data Analysis (24) Data Analytics (16) data management (15) Data Science (225) Data Strucures (14) Deep Learning (75) Django (16) Downloads (3) edx (21) Engineering (15) Euron (30) Events (7) Excel (17) Finance (9) flask (3) flutter (1) FPL (17) Generative AI (48) Git (6) Google (47) Hadoop (3) HTML Quiz (1) HTML&CSS (48) IBM (41) IoT (3) IS (25) Java (99) Leet Code (4) Machine Learning (197) Meta (24) MICHIGAN (5) microsoft (9) Nvidia (8) Pandas (12) PHP (20) Projects (32) Python (1219) Python Coding Challenge (898) Python Quiz (348) Python Tips (5) Questions (2) R (72) React (7) Scripting (3) security (4) Selenium Webdriver (4) Software (19) SQL (45) Udemy (17) UX Research (1) web application (11) Web development (7) web scraping (3)

Followers

Python Coding for Kids ( Free Demo for Everyone)