- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions

# Program to find how many ways we can climb stairs in Python

Suppose we have a staircase with n steps, and we can climb up either 1 or 2 steps at a time. We have to define a function that returns the number of unique ways we can climb the staircase.

The order of the steps should not be changed, so each different order of steps counts as a way. If the answer is very large then mod the result by 10^9 + 7

So, if the input is like n = 5, then the output will be 8, as there are 8 unique ways −

- 1, 1, 1, 1, 1
- 2, 1, 1, 1
- 1, 2, 1, 1
- 1, 1, 2, 1
- 1, 1, 1, 2
- 1, 2, 2
- 2, 1, 2
- 2, 2, 1

To solve this, we will follow these steps −

- dp:= an array of size n+1, and fill with 0
- dp[1]:= 1
- for i in range 2 to n+1, do
- dp[i]:= dp[i-1]+dp[i-2]

- return last element of dp mod m

Let us see the following implementation to get better understanding −

## Example

m =(10**9)+7 class Solution: def solve(self, n): dp=[0 for _ in range(n+2)] dp[1]=1 for i in range(2,n+2): dp[i]=dp[i-1]+dp[i-2] return dp[-1] % m ob = Solution() print(ob.solve(5))

## Input

5

## Output

8

- Related Articles
- Program to find how many ways we can climb stairs (maximum steps at most k times) in Python
- Program to find number of ways we can reach to the next floor using stairs in Python
- Reena climbs up five stairs every second and than climb down two stairs over the next second .how many seconds will she take to climb 60 stairs?
- Program to find to get minimum cost to climb at the top of stairs in Python?
- Program to count how many ways we can divide the tree into two trees in Python
- Program to check how many ways we can choose empty cells of a matrix in python
- Program to count how many ways we can cut the matrix into k pieces in python
- Program to find maximum how many water bottles we can drink in Python
- Program to find how many total amount of rain we can catch in Python
- C++ program to count in how many ways we can paint blocks with two conditions
- In how many ways we can concatenate Strings in Java?
- Program to find number of ways we can decode a message in Python
- Program to find number of ways we can split a palindrome in python
- C++ program to count in how many ways we can minimize cable length to connect computers
- In how many ways can we find a substring inside a string in javascript?

Advertisements