【发布时间】:2018-11-22 08:47:30
【问题描述】:
我有这个使用 numpy 的 python 代码:
import numpy as np
table = np.array([[23, 54, 12],
[17, 32, 25],
[43, 19, 11],
[31, 22, 10],
[21, 19, 35]])
r, c = table.shape
out = np.zeros((r,c))
out[0, :] = np.cumsum(table[0,:])
out[:, 0] = np.cumsum(table[:,0])
for j in range(1, c):
for i in range(1, r):
out[i,j] = max( out[i-1,j], out[i,j-1] ) + table[i,j]
out[-1,-1]
我首先计算数组“out”的第一行和第一列,而其余的值是用 for 循环内的等式计算的。我只对表格的最后一个值( out[-1,-1] )感兴趣,我想尽可能快地完成它。我可以以某种方式删除两个“for”循环吗??
【问题讨论】:
-
你尝试了什么?
-
我尝试让它递归但没有成功,但我仍然认为它不会像那样快。我真的需要尽快完成
-
欢迎来到 SO。请尝试从另一个用户的角度来思考,他们对您的问题一无所知,这可能在您的脑海中已经存在数天或数周。所以,minimal reproducible example 和 How to Ask 在这里申请。我想说您的代码甚至没有运行,因为您忘记了表定义中的外括号...
标签: python performance numpy