Friday, 12 January 2024

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

 


Code: 

def fun(num):

    if num > 10:

        return num - 10

    return fun(fun(num + 11))

print(fun(5))

Solution and Explanantion: 


The output of the code is 1.

Here's a breakdown of how the code works:

Function Definition:

The code defines a recursive function named fun that takes a single argument, num.

Base Case:

The if statement checks if num is greater than 10. If it is, the function returns num - 10. This is the base case that stops the recursion.

Recursive Calls:

If num is not greater than 10, the function calls itself twice, creating two recursive calls:
fun(fun(num + 11))
The inner call fun(num + 11) adds 11 to num and passes the result to the fun function again.
The outer call takes the result of the inner call and passes it to the fun function once more.

Execution Flow:

When you call fun(5), here's what happens:
5 is not greater than 10, so the function calls fun(fun(16)).
The inner call fun(16) now executes. 16 is greater than 10, so the base case triggers and returns 16 - 10 = 6.
The outer call now has 6 as its argument. 6 is not greater than 10, so it calls fun(fun(17)).
The inner call fun(17) executes. 17 is greater than 10, so the base case returns 17 - 10 = 7.
The outer call now has 7 as its argument. 7 is not greater than 10, so it calls fun(fun(18)).
This process continues until fun(25) is reached. At this point, the base case returns 25 - 10 = 15.
The values start propagating back through the recursive calls, eventually leading to the final return value of 1.
Key Points:

The code demonstrates recursion, where a function calls itself within its own definition.
The base case is crucial to prevent infinite recursion and ensure the function eventually terminates.
Recursive functions can be helpful for solving problems that can be broken down into smaller, self-similar subproblems. 

0 Comments:

Post a Comment

Popular Posts

Categories

100 Python Programs for Beginner (53) AI (34) Android (24) AngularJS (1) Assembly Language (2) aws (17) Azure (7) BI (10) book (4) Books (173) C (77) C# (12) C++ (82) Course (67) Coursera (226) Cybersecurity (24) data management (11) Data Science (128) Data Strucures (8) Deep Learning (20) Django (14) Downloads (3) edx (2) Engineering (14) Excel (13) Factorial (1) Finance (6) flask (3) flutter (1) FPL (17) Google (34) Hadoop (3) HTML&CSS (47) IBM (25) IoT (1) IS (25) Java (93) Leet Code (4) Machine Learning (59) Meta (22) MICHIGAN (5) microsoft (4) Nvidia (3) Pandas (4) PHP (20) Projects (29) Python (932) Python Coding Challenge (363) Python Quiz (24) Python Tips (2) Questions (2) R (70) React (6) Scripting (1) security (3) Selenium Webdriver (3) Software (17) SQL (42) UX Research (1) web application (8) Web development (2) web scraping (2)

Followers

Person climbing a staircase. Learn Data Science from Scratch: online program with 21 courses