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

标签 python numpy

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/

相关文章:

python - 我如何评估我的技术?

python - 在 "for"循环中一个一个添加数组元素?

python - 在python中打印特定日期

python - Scikit Learn 回归 : Design matrix X too big for regression. 我该怎么办?

python - 从 mysql 检索相等的值

python - 尝试将一列字符串转换为 float

python - 为什么调和后的mcmc fit 转换不好?

python - 从 python 数组中选择行

python - 为什么 numpy.zeros 不在创建时分配所有内存?我怎么能强制它呢?

python - for 循环生成多个 polyfit 散点图