This community-built FAQ covers the “Stairmaster” code challenge in Python. You can find that challenge here, or pick any challenge you like from our list.

Top Discussions on the Python challenge Stairmaster

There are currently no frequently asked questions or top answers associated with this challenge – that’s where you come in! You can contribute to this section by offering your own questions, answers, or clarifications on this challenge. Ask a question or post a solution by clicking reply () below.

If you’ve had an “aha” moment about the concepts, formatting, syntax, or anything else with this challenge, consider sharing those insights! Teaching others and answering their questions is one of the best ways to learn and stay sharp.

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply () below!
You can also find further discussion and get answers to your questions over in #get-help.

Agree with a comment or answer? Like () to up-vote the contribution!

Essentially, you want to add the number of ways for stairmaster( n -1) , stairmaster(n-2), and stairmaster(n-3), to get the value of stairmaster(n). Since it’s really easy to calculate stairmaster() for n = 1, 2, or 3, we can just include that at the beginning of the function to give us a starting point for bigger numbers.

Then we just run a for loop for 4 to n and on each iteration:

We set d = sum of the three previous values of a, b, and c

We update the values of a, b, c so that they are the values needed for the next value of i.

We are then counting up to stairmaster (n) eventually. Once i reaches n, d is the sum of the 3 previous values of d, which is the number of permutations of 1, 2, 3 that equal n number of stairs, so we terminate the loop and return d as our answer.

def stairmaster(n):
a = 1
b = 2
c = 4
d = 0 # fourth variable (placehold for when n > 3)
if (n == 0 or n == 1 or n == 2):
return n
if (n == 3):
return c
for i in range(4,n+1):
# starting from 4 because we already know the solution for, 1, 2, or 3 stairs
d = c + b + a # already counted for 3 stairs
a = b
b = c
c = d
return d
print(stairmaster(10))

def stairmasterDP(n):
memo = {0:1,1:1,2:2,3:4}
if n in memo:
return memo[n]
else:
for i in range(4,n+1):
memo[i] = memo[i-1] + memo[i-2] + memo[i-3]
return memo[n]
print(stairmasterDP(10))

This challenge is like trying to find Fibonacci numbers, but with base cases: 1, 2, 4.

I used loops instead of recursion, and I stored the relevant previous values in a list.

def stairmaster(n, k = 3):
if (n <= 0):
return 0;
elif (n <= k):
return 2 ** (n - 1)
recursive = [2 ** i for i in range(k)]
for i in range(k + 1, n + 1):
current = sum(recursive)
recursive.pop(0)
recursive.append(current)
return current

A list probably wasn’t the best data structure to use for this. Maybe a deque would be better.