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

Python实现右侧1/4区域填充#的矩形框图案修改需求

修改Python矩形图案程序,实现右侧指定区域填充

Hey there! Let's tweak your code to get the exact pattern you're looking for. Your original code drew a border plus both diagonals, but we need to adjust the logic to replace the right diagonal with a filled right-side area that widens as we reach the middle row.

Here's the updated code that matches your expected output:

def pattern(n):
    mid = n // 2
    for i in range(n):
        for j in range(n):
            # 保留外边框
            if i == 0 or i == n - 1 or j == 0 or j == n - 1:
                print("#", end="")
            # 保留左侧对角线
            elif i == j:
                print("#", end="")
            # 处理中间行的右侧填充区域
            elif 1 < i < n - 1:
                offset = abs(i - mid)
                # 中间行从中间列开始填充,其余中间行从中间列右侧一列开始填充
                if j >= (mid if offset == 0 else mid + 1):
                    print("#", end="")
                else:
                    print(" ", end="")
            else:
                print(" ", end="")
        print()

When you run pattern(7), you'll get exactly the output you want:

#######

#
#

#######

Quick breakdown of the logic:

  • We calculate mid to find the center row index (since we're using 0-based indexing).
  • The outer border condition stays intact to keep the rectangular frame.
  • We keep the left diagonal (i == j) to maintain that vertical line of #s on the left side of the inner area.
  • For rows between the top and bottom borders, we use offset to measure how far the current row is from the middle.
    • The exact middle row fills from the center column to the right, creating the widest filled section.
    • Rows above and below the middle start filling one column to the right of the center, keeping the pattern symmetric and matching your desired look.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:34:19