繁体   English   中英

在 Python 中创建对称图案

[英]Creating a symmetrical pattern in Python

Python(和 StackOverflow)新手在这里。 我正在尝试在 Python 中创建一个在输出中仅使用“#”和“”的对称形状。

这是我需要创建的形状:

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

一些快速信息是它具有:

  • 每行 14 个字符
  • 上半部分是四行,然后形状反过来

我的想法是尝试将以下变量与各自的值一起使用,并使用'while'输出'#'和''。 中间空间是 (14 - middleSpace)。

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

这是上一个练习的代码。 从那以后,我在这里搜索并看到人们使用“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')

这是一个列表推导,您可以将其转换回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))

输出:

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

暂无
暂无

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

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