如何用Python实现参数控制的特殊钻石图案?
修正Python钻石图案打印函数
需要实现一个Python函数,根据输入的高度参数打印特定格式的钻石图案。以参数6为例,图案规则如下:
- 整体结构包含上半部分5行、中间1行共享星号、下半部分5行
- 上半部分前2行输出星号(
*),剩余行替换为1 # 1格式,且#两侧的空格数随行数增加而递增 - 下半部分对应上半部分的行,前3行替换为
2 ^ 2格式,最后2行回到星号输出
用户提供的代码运行后存在两个问题:
- 上半部分
1 # 1行的空格布局错误,导致格式不对齐 - 下半部分未按规则替换为
2 ^ 2,全部输出星号
用户原代码:
def print_half_diamond(height): if height <= 0: print("Height must be a positive integer.") return for i in range(1, height + 1): spaces = " " * (height - i) line = "" if i == 1 or i == 2: line = "*" * (2 * i - 1) else: line = "1" + " " * (2 * (i - 2) + 1) + "#" + " " * (2 * (height - i)) + "1" print(spaces + line) print("*" * (2 * height - 1)) for i in range(height - 1, 0, -1): spaces = " " * (height - i) stars = "*" * (2 * i - 1) print(spaces + stars) print_half_diamond(6)
实际错误输出:
* *** 1 # 1 1 # 1 1 # 1 1 #1 *********** ********* ******* ***** *** *
修正后的代码
def print_diamond(height): if height <= 0: print("Height must be a positive integer.") return # 打印上半部分 for i in range(1, height): leading_spaces = " " * (height - i) if i == 1 or i == 2: line = "*" * (2 * i - 1) else: # 保证当前行总长度和对应星号行一致:2*i-1 total_length = 2 * i - 1 # 减去"1 # 1"的固定长度5,剩余空格平分到#两侧 remaining_spaces = total_length - 5 left_spaces = " " * (remaining_spaces // 2) right_spaces = " " * (remaining_spaces // 2) line = f"1{left_spaces}#{right_spaces}1" print(leading_spaces + line) # 打印中间共享星号行 print("*" * (2 * height - 1)) # 打印下半部分 for i in range(height - 1, 0, -1): leading_spaces = " " * (height - i) if i == 1 or i == 2: line = "*" * (2 * i - 1) else: total_length = 2 * i - 1 remaining_spaces = total_length - 5 left_spaces = " " * (remaining_spaces // 2) right_spaces = " " * (remaining_spaces // 2) line = f"2{left_spaces}^{right_spaces}2" print(leading_spaces + line) print_diamond(6)
关键修正点
上半部分空格对齐修正:
放弃原有的错误空格计算逻辑,改为基于当前行总长度(与对应星号行一致),减去1 # 1的固定长度后,将剩余空格平均分配到#两侧,确保整体格式对齐。下半部分规则实现:
对应上半部分的逻辑,当i大于2时输出2 ^ 2格式,空格计算方式与上半部分一致;仅i为1或2时输出星号。循环范围调整:
原上半部分循环range(1, height+1)会多打印一行,改为range(1, height),保证上半部分行数为height-1,符合参数6时上半部分5行的要求。
运行修正后的代码,输出符合要求的图案:
* *** 1 # 1 1 # 1 1 # 1 1 # 1 *********** 1 # 1 1 # 1 1 # 1 1 # 1 *** *
内容的提问来源于stack exchange,提问作者user3852473
相关产品推荐
相关产品推荐

