Reducing spaces between the character python

Question:

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.

Asked By: Jaffer Wilson

||

Answers:

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
Answered By: Ecir Hana

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.

Answered By: rzzzwilson
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.