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

如何实现Python的render_plot函数 基于指定坐标绘制带边框星号点阵图

完整实现代码

def render_plot(plot):
    # 计算x、y轴的取值范围
    xs, ys = zip(*plot)
    min_x, max_x = min(xs), max(xs)
    min_y, max_y = min(ys), max(ys)
    # 绘图区域总宽度(包含左右两侧边框)
    total_width = max_x - min_x + 3
    res = []
    # 生成顶部边框
    res.append('#' * total_width)
    # 从y轴最大值向下遍历,逐行绘制内容
    for y in range(max_y, min_y - 1, -1):
        line = ['#']
        for x in range(min_x, max_x + 1):
            line.append('*' if (x, y) in plot else ' ')
        line.append('#')
        res.append(''.join(line))
    # 生成底部边框
    res.append('#' * total_width)
    # 拼接所有行返回结果
    return '\n'.join(res)

核心调整说明

  • 修正了原代码变量名不一致、width拼写错误的问题,如果需要保留原参数名a,只要把内部用到plot的地方统一替换为a即可
  • 调整了坐标遍历逻辑:y轴从大到小遍历匹配输出从上到下的顺序,x轴从最小值到最大值遍历,直接判断坐标(x,y)是否在传入的集合中,不需要额外做坐标偏移转换
  • 统一处理边框逻辑:上下边框用对应长度的#直接生成,每一行的首尾固定加#作为左右边框
  • 用列表暂存每行内容最后统一拼接,比字符串逐次累加的效率更高

测试示例

传入题目给出的坐标集测试:

points = [(2, 3), (-1, 2), (1, -1), (0, 1)]
print(render_plot(points))

输出结果和题目给出的示例完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 15:24:03