Wednesday, 4 June 2025

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

 


Code Explanation:

 1. Importing the LRU Cache Decorator
from functools import lru_cache
functools is a standard Python module that provides tools for functional programming.
lru_cache is a decorator for memoization – it caches the results of expensive function calls so they don’t need to be recomputed.
LRU stands for Least Recently Used, which is a cache strategy.

 2. Decorating the Fibonacci Function with @lru_cache
@lru_cache(maxsize=None)
This decorator wraps the fib() function to automatically cache its return values.
maxsize=None means the cache can grow without limit – all results will be stored.
So if you call fib(5) once, its value is stored. Next time, it returns the cached result instantly.

3. Defining the Recursive Fibonacci Function
def fib(n):
Defines a function fib to compute the n-th Fibonacci number.
Takes one parameter n (an integer).

4. Handling the Base Cases
    if n < 2:
        return n
The base case of the Fibonacci sequence:
fib(0) returns 0
fib(1) returns 1
For n < 2, the function just returns n.

 5. Recursive Case for Fibonacci
    return fib(n-1) + fib(n-2)
If n >= 2, compute recursively using:
fib(n) = fib(n-1) + fib(n-2)
This mirrors the Fibonacci sequence:
fib(2) = fib(1) + fib(0) = 1 + 0 = 1
And so on...
Thanks to @lru_cache, repeated calls to fib(n-1) or fib(n-2) are fast after the first computation.

 6. Calling the Function and Printing the Result
print(fib(10))
Calls the fib() function with n = 10.
Computes the 10th Fibonacci number.

Output will be:
55

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)