You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改Python代码生成指定的字母对称镂空图案?

需求:修改Python代码生成指定字母对称镂空图案

要生成的目标图案如下:

A B C D E D C B A 
A B C D   D C B A   
A B C       C B A     
A B           B A       
A               A

现有待修改代码:

n = int(input('\nEnter the No. of rows : '))
n=n//2+1

print('\n')
# this is a never ending loop
r=n
i=-1
s=chr(64+1)

while r>=n:
 c=j=1
 while c<=n*2-1:
  print(s if c<=r else ' ',end='')
  if c==n: j=-1
  c=c+j
 print()
 if r==1: i=1
 r=r+i
 if i==1 and r>n:
   break

之前实现的矩形内嵌空心菱形代码(希望沿用此结构修改):

n = int(input('\nEnter the No. of rows : '))
n=n//2+1
print('\n')

r=n
i=-1
while r<=n:
 c=j=1
 while c>=1:
  print('*' if c<=r else ' ',end='')
  if c==n: j=-1
  c=c+j
 print()
 if r==1: i=1
 r=r+i

print()

修改后的代码及说明

直接沿用你熟悉的菱形代码结构,调整字母输出和空格填充逻辑即可:

n = int(input('\nEnter the No. of rows : '))
print('\n')

r = n
i = -1
while True:
    c = j = 1
    while c <= 2 * n - 1:
        # 判断当前列是否在需要显示字母的范围内
        if c <= r or c >= 2 * n - r:
            # 输出对应字母+空格
            print(chr(64 + c), end=' ')
        else:
            # 输出两个空格保证对齐
            print('  ', end='')
        if c == n:
            j = -1
        c += j
    print()
    # 到第1行就停止循环
    if r == 1:
        break
    r += i

关键修改点:

  1. 移除原代码中n=n//2+1的处理,输入的n直接对应最大字母的序号(比如输入5对应E,生成5行)。
  2. 替换固定字母s的输出逻辑,根据当前列c的位置生成对应字母chr(64 + c)。
  3. 调整空格填充:当列不在字母范围内时,输出两个空格,匹配字母+空格的宽度,保证整体对齐。
  4. 简化循环终止条件,只需要从n递减到1就停止,无需递增回去(目标图案只有从上到下的递减部分)。

输入5运行代码,就能得到你要的目标图案。

内容的提问来源于stack exchange,提问作者Harshul

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 22:35:07