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