Coding Problem 1

      Number of Ways to Climb the Stairs 
                                                      asked by Amazon

Ques. There is a Staircase with N steps, and you can climb only certain number of steps at a time given in the list. Write the function which can return the total number of unique ways to climb the staircase using only given number of steps. 

For example - If N = 4, and X = [1, 2] then there are 5 ways to climb the stair.
                        1st way = 1, 1, 1, 1
                        2nd way = 2, 1, 1
                        3rd way = 1, 2, 1
                        4th way = 1, 1, 2
                        5th way = 2, 2
In the above example you have 4 stairs and you can climb only 1 or 2 steps at a time given in list X. Take N and X as a input.
Lets code it!

Solution.  
We can solve it using recursion. We take one step at a time and then repeat the same procedure for the remaining number of steps. Lets solve it for the given example first -

n = 4
def staircase(n):
      if n<=1:
           return 1
      return staircase(n-1) + staircase(n-2)

So what we are doing here is first we reduce the 1 and 2 steps from the original number of steps and call the same procedure for remaining steps simultaneously. Now if we reached only 1 remaining step or less then we can have only one option to climb it and return 1. Thats our base condition.
Now we can generalize this method for any number of given steps. Suppose in X we have multiple values then we can subtract each value from the total number of stairs simultaneously and call the same procedure for the remaining number of stairs. We will take X in the form of list. We will enter the number using space then split it and add them to the list.

N = int(input("Enter the total number of stairs: "))
X = [int(i) for i in input("enter the number of steps at a time: ").split()]
print("X is: ", X)

def staircase(N, X):
        if N < 0:
            return 0
        elif N == 0:
            return 1
        else:
            return sum(staircase(N-x, X) for x in X)   # here we are taking each value from X and reducing them from total number of stairs and calling same procedure for remaining number of stairs

print("Total number of ways are: {0}".format(staircase(N, X)))

Output : Enter total number of stairs: 4
                   enter the number of steps at a time: 1 3 5
                   X is: [1, 3, 5]
                   Total number of ways are: 3

Explanation - Ways are = [1, 1, 1, 1], [1, 3], [3, 1]. There will be no use of 5 because it exceeds the total number of stairs given and similarly for [3, 3].

Comments

Popular posts from this blog

Coding Problem 10

Coding Problem 3

Coding Problem 9