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

AI (33) Android (24) AngularJS (1) Assembly Language (2) aws (17) Azure (7) BI (10) book (4) Books (146) C (77) C# (12) C++ (82) Course (67) Coursera (198) Cybersecurity (24) data management (11) Data Science (106) Data Strucures (8) Deep Learning (13) Django (14) Downloads (3) edx (2) Engineering (14) Excel (13) Factorial (1) Finance (6) flask (3) flutter (1) FPL (17) Google (21) Hadoop (3) HTML&CSS (47) IBM (25) IoT (1) IS (25) Java (93) Leet Code (4) Machine Learning (46) Meta (18) MICHIGAN (5) microsoft (4) Nvidia (1) Pandas (3) PHP (20) Projects (29) Python (893) Python Coding Challenge (285) Questions (2) R (70) React (6) Scripting (1) security (3) Selenium Webdriver (2) Software (17) SQL (42) UX Research (1) web application (8)

Followers

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