How to "upgrade" hourglass pattern generator?

137 views Asked by At

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)
1

There are 1 answers

1
python_user On BEST ANSWER

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.

def hour_glass(n, character, width=None):
    if width is None:
        width = n
    if n == 1:
        print(character.center(width))
        return
    to_print = (character * n).center(width)
    print(to_print)
    hour_glass(n - 2, character, width)
    print(to_print)

Output

hour_glass(7, 'X')

XXXXXXX
 XXXXX 
  XXX  
   X   
  XXX  
 XXXXX 
XXXXXXX

hour_glass(5, 'X')

XXXXX
 XXX 
  X  
 XXX 
XXXXX