简体   繁体   English

在 Python 中创建对称图案

[英]Creating a symmetrical pattern in Python

Python (and StackOverflow) newbie here. Python(和 StackOverflow)新手在这里。 I am trying to create a symmetrical shape in Python that uses only '#' and ' ' in the output.我正在尝试在 Python 中创建一个在输出中仅使用“#”和“”的对称形状。

This is the shape I need to create:这是我需要创建的形状:

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

Some quick info is that it has:一些快速信息是它具有:

  • 14 characters per row每行 14 个字符
  • 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 ' '.我的想法是尝试将以下变量与各自的值一起使用,并使用'while'输出'#'和''。 The middle space would be (14 - middleSpace).中间空间是 (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.从那以后,我在这里搜索并看到人们使用“for i in range”创建模式,但我不知道如何在这个新练习中使用它。

#   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')

Here's a list comprehension that you can potentially convert back into a for/while loop:这是一个列表推导,您可以将其转换回for/while循环:

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:输出:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM