如果调用以下代码的 np.sum() 如何减少数量?(测试规则规定只能进行 2 次调用)



first_half_second_half 获取形状 (n,2*m( 的二维数组作为参数。函数的输出应该是一个矩阵,其中包含输入中前 m 个元素的总和大于行上最后 m 个元素的总和的行

此解决方案有效,但对 np.sum(( 的调用次数取决于测试大小数据。有没有可能的方法可以仅使用两个 np.sum(( 调用来实现这一点

def first_half_second_half(a):
len=int(a.shape[1]/2)
for i in range(a.shape[0]):
if np.sum(a[i,:len])>np.sum(a[i,len:]):
arr.append(a[i,:])
return np.array(arr)
a = np.array([[1, 3, 4, 2],
[2, 2, 1, 2]])
first_half_second_half(a)
**array([[2, 2, 1, 2]])**

对于随机测试数据: 20 != 2 : 预计正好两次调用函数 np.sum!

你可以这样做


m = a.shape[1]//2 # assuming it has even number of columns
sum1 = np.sum(a[:,:m], axis=1) #sum first half
sum2=np.sum(a[:,m:], axis=1) #sum second half
a[sum1>sum2] # get rows whose 1st half sum is greater

最新更新