I'm making an exercise with patterns in Python and I've did a hourglass pattern for n=5 but when I'm trying with other odd number e.g. n
==7, it's destroyed. Any suggestions how to upgrade my code?
def hourglass(num_of_rows):
#upper piece
for i in range(num_of_rows-(num_of_rows//2)):
print(' '*i+ character*(num_of_rows-2*i))
#lower piece without the middle one
for j in range(num_of_rows-1-(num_of_rows//2), -1, -2):
print(' '*(j-1) +character*(num_of_rows-j))
num_of_rows=5
character = 'x'
hourglass(num_of_rows)
Not an exact upgrade to what you have done, you can use recursion to get what you want. This however will not work if
n
is an even number, I dont know how the hour glass will be for an even number, I can change it accordingly if you specify.str.center
can be used to do the padding without doing any of those math. Let me know if any explanation is needed.Output