Saturday, 20 September 2025

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

 


Code Explanation:

1. Importing lru_cache
from functools import lru_cache

functools is a Python module with higher-order functions and decorators.

lru_cache = Least Recently Used cache.

It stores results of function calls so repeated inputs don’t need recalculation.

2. Applying the Decorator
@lru_cache(maxsize=None)

This tells Python to cache all results of the function that follows.

maxsize=None → the cache can grow indefinitely.

Whenever the function is called with the same argument, the result is retrieved from memory instead of being computed again.

3. Defining the Fibonacci Function
def fib(n):
    if n < 2:
        return n
    return fib(n-1) + fib(n-2)

Step-by-step:
Base case:
If n < 2 (i.e., n == 0 or n == 1), return n.

fib(0) = 0

fib(1) = 1

Recursive case:
Otherwise, return the sum of the two previous Fibonacci numbers:

fib(n) = fib(n-1) + fib(n-2)

4. Calling the Function
print(fib(10))

Starts the recursive calculation for fib(10).

Uses the formula repeatedly until it reaches the base cases (fib(0) and fib(1)).

Thanks to lru_cache, each intermediate result (fib(2) … fib(9)) is computed once and reused.

5. Fibonacci Sequence (0 → 10)
fib(0) = 0
fib(1) = 1
fib(2) = 1
fib(3) = 2
fib(4) = 3
fib(5) = 5
fib(6) = 8
fib(7) = 13
fib(8) = 21
fib(9) = 34
fib(10) = 55

Final Output
55

500 Days Python Coding Challenges with Explanation


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)