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
关于python - 如果以下代码调用 np.sum() 如何减少数量?(测试规则规定只能进行 2 次调用),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57738793/