Sunday, 1 June 2025

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

 


Code Explanation:

1. Function Definition
def climb_stairs(n):
Defines a function named climb_stairs that takes one argument n, representing the number of steps.

2. Base Case Check
    if n <= 2:
        return n
If n is 1 or 2, return n directly because:

For 1 step, there is only 1 way.

For 2 steps, there are 2 ways (1+1 or 2).

3. Initialize Variables
    a, b = 1, 2
Initialize two variables:
a represents the number of ways to climb to step 1 (which is 1).
b represents the number of ways to climb to step 2 (which is 2).

4. Loop Through Steps 3 to n
    for _ in range(3, n + 1):
        a, b = b, a + b
For each step from 3 to n:

Update a to the previous b (ways to reach the previous step).

Update b to the sum of the previous a and b (ways to reach current step).

This uses the Fibonacci pattern because ways to get to step i = ways to get to i-1 + ways to get to i-2.

5. Return Result
    return b
After the loop, b holds the total number of ways to reach step n, so return it.

6. Function Call and Output
print(climb_stairs(5))
Calls the function with n = 5 and prints the result.
Output will be 8, which is the number of ways to climb 5 steps.

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)