Home > Software design >  Creating a symmetrical pattern in Python
Creating a symmetrical pattern in Python

Time:07-07

Python (and StackOverflow) newbie here. I am trying to create a symmetrical shape in Python that uses only '#' and ' ' in the output.

This is the shape I need to create:

#            #
 ##        ##
  ###    ###
   ########
   ########
  ###    ###
 ##        ##
#            #

Some quick info is that it has:

  • 14 characters per row
  • top half is four rows, and then the shape inverts the other way

My thinking has been to try and use the following variables with the respective values, and using 'while' to output the '#' and ' '. The middle space would be (14 - middleSpace).

sidespace = 0 (increments by 1 per row)
hash = 1 (this increments by 1 per row)
middleSpace = 2 (increment by 4 per row)

Here is the code for the previous exercise. I've since searched on here and seen people creating patterns using 'for i in range', but I can't figure out how to use that for this new exercise.

#   Exercise 2-2
#
#   Using only single-character output statements that output a hash mark,
#   a space, or an end-of-line symbol, write a program that outputs the
#   following shape:
#
#      ##
#     ####
#    ######
#   ########
#   ########
#    ######
#     ####
#      ##
#


# Top Half
toprows = 1

while toprows <= 4:
    tophash = 1
    topspace = 1

    while topspace <= 3 - (toprows -1):
        print(' ', end=' ')
        topspace  = 1

    while tophash <= 2   2 * (toprows - 1):
        print('#', end=' ')
        tophash  = 1
    toprows  = 1
    print('\n')


# Bottom Half

myrow = 1

while myrow <= 4:
    hash = 0
    space = 1

    while space <= myrow - 1:
        print(' ', end=' ')
        space  = 1

    while hash <= 9 - 2* myrow:
        print('#', end=' ')
        hash  = 1

    myrow  = 1
    print('\n')

CodePudding user response:

Here's a list comprehension that you can potentially convert back into a for/while loop:

rows = [' '*i   '#'*(i 1)   ' '*(14-2*i-2*(i 1))   '#'*(i 1)   ' '*i for i in [*range(4), *reversed(range(4))]]
print('\n'.join(rows))

Output:

#            #
 ##        ##
  ###    ###
   ########
   ########
  ###    ###
 ##        ##
#            #
  • Related