DC TC DC TC - 7 months ago 9
Python Question

HackerRank Staircase Python

I am trying to solve a problem in HackerRank and I am having an issue with my submission. My code works in PyCharm but HackerRank is not accepting my submission.

Here is the problem I am trying to solve: https://www.hackerrank.com/challenges/staircase

Here is my code:

def staircase(num_stairs):
n = num_stairs - 1
for stairs in range(num_stairs):
print ' ' * n, '#' * stairs
n -= 1
print '#' * num_stairs
staircase(12)


Any ideas why HackerRank is not accpeting my answer?

Answer

Your output is incorrect; you print an empty line before the stairs that should not be there. Your range() loop starts at 0, so you print n spaces and zero # characters on the first line.

Start your range() at 1, and n should start at num_stairs - 2 (as the , in print adds a space:

def staircase(num_stairs):
    n = num_stairs - 2
    for stairs in range(1, num_stairs):
        print ' ' * n, '#' * stairs
        n -= 1
    print '#' * num_stairs

You can simplify this to one loop:

def staircase(num_stairs):
    for stairs in range(1, num_stairs + 1):
        print ' ' * (num_stairs - stairs) + '#' * stairs

Note that I use concatenation now to combine spaces and # characters, so that in the last iteration of the loop zero spaces are printed and num_stairs # characters.