Home > Software design >  Recursion - Stairs Problem - Why doesn't my code work? - Python
Recursion - Stairs Problem - Why doesn't my code work? - Python

Time:01-07

Problem:

In this problem, the scenario we are evaluating is the following: You're standing at the base of a staircase and are heading to the top. A small stride will move up one stair, and a large stride advances two. You want to count the number of ways to climb the entire staircase based on different combinations of large and small strides. For example, a staircase of three steps can be climbed in three different ways: three small strides, one small stride followed by one large stride, or one large followed by one small. Write a recursive method waysToClimb that takes a non-negative integer value representing a number of stairs and prints each unique way to climb a staircase of that height, taking strides of one or two stairs at a time. Your method should output each way to climb the stairs on its own line, using a 1 to indicate a small stride of 1 stair, and a 2 to indicate a large stride of 2 stairs. For example, the call of waysToClimb(3) should produce the following output:

[1, 1, 1]
[1, 2]
[2, 1]

My Code:

def waysToClimb(n,a=[]):
    if n == 0:
        print(a)
    if n >= 1:
        a.append(1)
        waysToClimb(n-1,a)
    if n >= 2:
        a.append(2)
        waysToClimb(n-2,a)

But for example when I type:

print(waysToClimb(3,[]))

The result is [2, 1] [2, 1, 1, 2] [2, 1, 1, 2, 1, 1]. Why doesn't my code work correctly?

EDIT: I was supposed to change "a" variable within function not outside it. I wrote fct(n,a [2]) instead of a.append(2) and it worked. Thanks for help all.

CodePudding user response:

Something, well, differently convoluted:

def ways2climb(n,sofar=[]):
    return [sofar] if n==0 else (ways2climb(n-2,sofar [2]) if n>=2 else [])   ways2climb(n-1,sofar [1])

CodePudding user response:

refer to this link

def way_to_climb(n, path=None, val=None):
path = [] if path is None else path

val = [] if val is None else val
if n==0:
   val.append(path)
elif n==1:
    new_path = path.copy()
    new_path.append(1)
    way_to_climb(n-1, new_path, val)
    
elif n>1:
    new_path1 = path.copy()
    new_path1.append(1)
    
    way_to_climb(n-1, new_path1, val)
    
    new_path2 = path.copy()
    new_path2.append(2)
    
    way_to_climb(n-2, new_path2, val)
return val

Scroll down the link mentioned and you will find the code i pasted here.

Already given by someone, this will help you out to figure out the correct answer.

  • Related