Tuesday, 17 June 2025

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

 


Code Explanation:

1. Importing lru_cache from functools
from functools import lru_cache
lru_cache stands for Least Recently Used Cache.
It’s a decorator that remembers the results of function calls, so if the same inputs occur again, it returns the cached result instead of recomputing.

2. Defining the Recursive Fibonacci Function with Caching
@lru_cache(maxsize=2)
def fib(n):
    return 1 if n < 2 else fib(n-1) + fib(n-2)
Key Points:
This defines a recursive Fibonacci function.
Base case:
fib(0) = 1
fib(1) = 1
Recursive case:
fib(n) = fib(n-1) + fib(n-2)
Decorated with @lru_cache(maxsize=2):
The cache will store only the last two most recently used results.
When a new call is added and the cache is full, the least recently used entry is removed.

3. Calling the Function
=print(fib(5))
What Happens Internally:
Let’s simulate the recursive calls with caching (maxsize=2):
fib(5)
= fib(4) + fib(3)
= (fib(3) + fib(2)) + (fib(2) + fib(1))
= ((fib(2) + fib(1)) + (fib(1) + fib(0))) + ((fib(1) + fib(0)) + 1)
But due to the limited cache (maxsize=2), the cache will only retain the two most recently used values during execution. This means:
Many results will be evicted before they can be reused.
You don’t get the full performance benefit that you would with a larger cache or unlimited size.

Result:
The output is still 8 (correct Fibonacci result for fib(5)), but with less efficiency due to constant cache eviction.

Why Use maxsize=2?
This small size shows how limited cache can impact performance — useful for experimentation or memory-constrained scenarios.
You'd typically use a larger maxsize (or None for unlimited) in real-world performance-sensitive recursive computations.

Final Output:
8

0 Comments:

Post a Comment

Popular Posts

Categories

100 Python Programs for Beginner (118) AI (152) Android (25) AngularJS (1) Api (6) Assembly Language (2) aws (27) Azure (8) BI (10) Books (251) Bootcamp (1) C (78) C# (12) C++ (83) Course (84) Coursera (298) Cybersecurity (28) Data Analysis (24) Data Analytics (16) data management (15) Data Science (217) Data Strucures (13) Deep Learning (68) Django (16) Downloads (3) edx (21) Engineering (15) Euron (30) Events (7) Excel (17) Finance (9) flask (3) flutter (1) FPL (17) Generative AI (47) 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 (186) Meta (24) MICHIGAN (5) microsoft (9) Nvidia (8) Pandas (11) PHP (20) Projects (32) Python (1218) Python Coding Challenge (884) Python Quiz (342) 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)