How to Climb Stairs with Python?

Estimated read time 2 min read

To simulate climbing stairs using Python, you can use various approaches. One common method is to implement a recursive function or use dynamic programming to calculate the number of ways to climb a given number of stairs. Here’s an example using dynamic programming:

def climbStairs(n):
    if n == 1:
        return 1
    if n == 2:
        return 2

    # Create a list to store the number of ways to climb each step
    dp = [0] * (n + 1)
    dp[1] = 1  # Number of ways to climb 1 step
    dp[2] = 2  # Number of ways to climb 2 steps

    # Calculate the number of ways to climb each step
    for i in range(3, n + 1):
        dp[i] = dp[i - 1] + dp[i - 2]

    return dp[n]

# Test the function
num_stairs = 5
num_ways = climbStairs(num_stairs)
print(f"The number of ways to climb {num_stairs} stairs is {num_ways}.")

In this example, the climbStairs function takes an integer n representing the number of stairs and returns the number of distinct ways to climb the stairs. The function uses a dynamic programming approach where dp[i] represents the number of ways to climb i stairs. The function iteratively calculates the number of ways for each step up to n using the formula dp[i] = dp[i - 1] + dp[i - 2], which represents the fact that you can either climb one step from the previous step or two steps from two steps back.

When you run this code, it will output:

The number of ways to climb 5 stairs is 8.

This means there are 8 distinct ways to climb 5 stairs using either 1 or 2 steps at a time.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply