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.
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
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.
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.
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
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.