Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HackerRank Staircase Python

Tags:

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?

like image 488
dericcain Avatar asked Jul 04 '15 15:07

dericcain


3 Answers

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 Multiple arguments to print() adds a space:

from __future__ import print_function

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.

Last but not least, you could use the str.rjust() method (short for “right-justify”) to supply the spaces:

def staircase(num_stairs):
    for stairs in range(1, num_stairs + 1):
        print(('#' * stairs).rjust(num_stairs))
like image 94
Martijn Pieters Avatar answered Nov 07 '22 18:11

Martijn Pieters


You can use rjust to justify the string to the right:

def staircase(n):
    for i in range(1, n+1):
         print(("#" * i).rjust(n))
like image 5
Kamil Sindi Avatar answered Nov 07 '22 19:11

Kamil Sindi


Another solution

n = int(raw_input())
s = '#'
for i in xrange( 1 , n+1):
    print " "*(n-i) + s*i
like image 2
Pankaj Kumar Avatar answered Nov 07 '22 18:11

Pankaj Kumar