python - 如何对子矩阵求和
问题描述
我需要为每个子矩阵制作值的总和。例如,如果我有 [[1,1,2],[2,3,4]],则结果矩阵将是:
M[0][0] = 1 M[0][1] = 1+1 = 2 M[0][2] = 1+1+2 = 4
M[1][0] = 1+2 = 3 M[1][1] = 1+1+2+3 = 7 M[1][2] = 1+1+2+2+3+4 = 13
或者
M = [[1,2,4],[3,7,13]]
我做了这个代码
`N = []
M = []
summ = 0
n= list(map(int, input().split()))
while n != []:
N.append(n)
n = list(map(int, input().split()))
for i in range(len(N)):
M.append([0 for i in range(len(N[0]))])
summ = 0
for j in range(len(N[0])):
summ += N[i][j]
M[i][j] = M[i-1][j] + summ `
问题是当矩阵很大时会变得非常慢。我需要在 0.5 秒内最大求解 100x100 矩阵
有谁能够帮我?无需导入包!!`
解决方案
为了速度,您真的希望使用NumPy,它除了为矩阵提供更简洁的代码外,还比基础 Python 快得多。从您的小示例中,您可以numpy.cumsum()
在不同的轴上使用两次:
import numpy as np
arr = np.array([[1,1,2],[2,3,4]])
out = arr.cumsum(axis=1).cumsum(axis=0)
print(out)
给出:
array([[ 1, 2, 4],
[ 3, 7, 13]], dtype=int32)
旁注:在 Windows 上,默认int
类型是 32 位,并且可能会在大矩阵/大数字上静默溢出,因此如果在 Windows 上cumsum()
,您可能会想要。arr = np.array([[1,1,2],[2,3,4]]).astype(np.int64)
时间:
arr = np.arange(10000).reshape(100, 100)
%timeit out = arr.cumsum(axis=1).cumsum(axis=0)
56.3 µs ± 4.96 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
因此,比您的要求快数千倍。
推荐阅读
- docker - 无法重启 Docker 机器
- python-3.x - 从 excel 到 python 代码的 vba 调用返回 excel 错误等待 ole 操作
- reactjs - 始终返回对象而不是承诺 useEffect()
- bash - 是否可以运行不包括最后一行的 shell 脚本?
- java - 对数组进行平方和排序的时间复杂度
- python - 如何在 PyCharm 替换功能中使用正则表达式占位符
- flutter - 如何使用 Dart 编辑 mp4 音频
- scala - Scala反射通过宇宙应用获取列表字段值
- c# - WPF、Excel 和 ContextMenu
- javascript - 使用 Node.Js 的 Lambda 函数