Python仅用#和空格打印指定14列宽对称图案的实现方法
Python实现指定对称#字图案打印
我是Python(及StackOverflow)新手,现尝试使用Python仅通过输出#和 (空格)两种字符绘制对称图形。
目标图案
需要实现的目标图案如下:
# # ## ## ### ### ######## ######## ### ### ## ## # #
图案规则
- 每行共14个字符
- 图案上半部分共4行,下半部分为上半部分的镜像反转
已有思路与参考代码
我最初的思路是定义如下初始值的变量,通过while循环输出#和 ,其中中间空格长度计算方式为14 - middleSpace:
sidespace = 0 # 每行递增1 hash_count = 1 # 每行递增1 middleSpace = 2 # 每行递增4
我之前完成过类似的图案打印练习,代码如下:
# 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_val = 0 space = 1 while space <= myrow - 1: print(' ', end=' ') space += 1 while hash_val <= 9 - 2* myrow: print('#', end=' ') hash_val += 1 myrow += 1 print('\n')
我在站内搜索时看到其他开发者使用for i in range的方式实现图案打印,但不知道如何将该方法套用到本次需求中,请问如何编写代码实现上述指定对称图案的打印输出?
实现方案
你最初的变量设计思路是正确的,每行结构可以拆分为「左侧缩进空格 + 左侧#块 + 中间间隔空格 + 右侧#块」,上半部分前3行左右#块被中间空格隔开,第4行中间空格长度为0,左右#块拼接为连续的8个#;下半部分直接复用/倒序输出上半部分的行即可,不需要重复编写对称逻辑。
方法1:for循环简洁实现
利用Python字符串乘法直接拼接每行内容,逻辑清晰代码量少:
LINE_WIDTH = 14 HALF_ROWS = 4 top_half = [] for i in range(HALF_ROWS): left_space = ' ' * i left_hash = '#' * (i + 1) # 最后一行中间无空格,其余行计算中间空格长度 if i == HALF_ROWS - 1: middle_space = '' else: mid_len = LINE_WIDTH - 2 * i - 2 * (i + 1) middle_space = ' ' * mid_len right_hash = left_hash top_half.append(left_space + left_hash + middle_space + right_hash) # 拼接上半部分和倒序的上半部分(即下半部分)后逐行打印 for line in top_half + top_half[::-1]: print(line)
方法2:while循环兼容写法
沿用你之前练习的嵌套while结构,保持单字符输出的写法要求:
# 打印上半部分 current_row = 1 while current_row <= 4: # 输出左侧空格 s = 1 while s <= current_row - 1: print(' ', end='') s += 1 # 输出左侧# h = 1 while h <= current_row: print('#', end='') h += 1 # 输出中间空格 mid_len = 14 - 2*current_row - 2*(current_row-1) if current_row <4 else 0 m = 1 while m <= mid_len: print(' ', end='') m += 1 # 输出右侧# h = 1 while h <= current_row: print('#', end='') h += 1 print() current_row += 1 # 打印下半部分,倒序遍历行号3、2、1即可 current_row = 3 while current_row >= 1: # 输出左侧空格 s = 1 while s <= current_row - 1: print(' ', end='') s += 1 # 输出左侧# h = 1 while h <= current_row: print('#', end='') h += 1 # 输出中间空格 mid_len = 14 - 2*current_row - 2*(current_row-1) m = 1 while m <= mid_len: print(' ', end='') m += 1 # 输出右侧# h = 1 while h <= current_row: print('#', end='') h += 1 print() current_row -= 1
注意:你之前的练习代码中给print设置了end=' ',会在每个输出字符后额外加一个空格,导致每行实际长度远超14,本次需求要求每行严格14个字符,单字符输出时不要追加额外空格。
内容的提问来源于stack exchange,提问作者Blu3byDo
相关产品推荐
相关产品推荐

