-1

I am trying to print the staircase pattern. I have written the code as follows:

def StairCase(n):
    for i in range(1, n + 1):
        stair_array = []
        j = 1
        while (j <= n):
            if (j <= i):
                stair_array.append('#')
            else:
                stair_array.append(' ')
            j = j + 1

        reversed_array = list(reversed(stair_array))
        for element in reversed_array:
            print "{}".format(element),
        print


_n = int(raw_input().strip("\n"))
StairCase(_n)

I got the output as:

6
          #
        # #
      # # #
    # # # #
  # # # # #
# # # # # #

The expected output is:

6
     #
    ##
   ###
  ####
 #####
######

As one can see my output is with spaces and is not acceptable as per original pattern. Kindly help.

Jaffer Wilson
  • 7,029
  • 10
  • 62
  • 139
  • @pissall Those are for making the stairs not for the space between the "#" – jadsq Nov 13 '17 at 09:33
  • BTW, you should seriously consider learning Python 3. Python 2 will reach its official End of Life in 2020. – PM 2Ring Nov 13 '17 at 09:45
  • The linked question show various ways to do this with the `print` statement, and the `print` function. However, it's probably better to do this using `''.join(element)`. Alternatively, you can use string multiplication instead of loops to make your strings. – PM 2Ring Nov 13 '17 at 09:54
  • @PM2Ring Still have 3 years... :D :P – Jaffer Wilson Nov 13 '17 at 09:54

2 Answers2

5

If you insist:

def StairCase(n):
    for i in range(1, n + 1):
        stair_array = []
        j = 1
        while (j <= n):
            if (j <= i):
                stair_array.append('#')
            else:
                stair_array.append(' ')
            j = j + 1

        reversed_array = list(reversed(stair_array))
        print ''.join(reversed_array)

but a much simpler way is to just:

def StairCase_new(n):
    for i in range(1, n + 1):
        print ' '*(n-i) + '#'*i
Ecir Hana
  • 10,864
  • 13
  • 67
  • 117
1

You have the answer, but in the original code you use the terminal ',' to suppress newlines. That adds a space after the thing you print. In python 2, of course.

rzzzwilson
  • 141
  • 5