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

不使用numpy如何用Python生成指定规则的N阶矩阵

矩阵生成代码修改方案

原代码存在的问题

  • 变量名拼写错误:fill_matrix 函数中定义行变量为row,实际追加到矩阵时用了未定义的fila
  • 作用域混淆:print_matrix 函数接收的参数是matriz,但内部打印时用了全局变量matrix,且行循环的长度变量写为row(正确应为rows)
  • 缺少核心填充逻辑:目前fill_matrix只生成了全0矩阵,没有按照规则填充对应数值

修改后的完整代码

def fill_matrix(n): 
    matrix = []
    for r in range(n):
        row = []
        # 计算当前行要填充的数值
        fill_val = n - r
        for c in range(n):
            # 前r+1个元素填fill_val,其余填0
            if c < r + 1:
                row.append(fill_val)
            else:
                row.append(0)
        matrix.append(row)
    return matrix

def print_matrix(matriz): 
    rows = len(matriz)
    columns = len(matriz[0])
    for f in range(rows):
        for c in range(columns):
            print("%3d" % matriz[f][c], end="")
        print()
       
# 主程序
side = int(input("Input the size of the matrix: ")) 
while side < 1:
    print("Size must be bigger than 0")
    side = int(input("Input the size of the matrix: "))
matrix = fill_matrix(side)
print_matrix(matrix)

核心修改点说明

  • 修正了所有变量名拼写、作用域错误,保证代码可正常运行
  • 在fill_matrix函数中新增填充逻辑:对第r行(索引从0开始),前r+1个元素赋值为n - r,其余保持0,完全符合题目要求的矩阵规则
  • 调整了矩阵初始化的逻辑,避免全局变量污染,代码更规范

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 21:09:03