如何获得Python中的数组的所有组合的产品总和?
问题描述:
我使用Python和
我给像 A =数组[1,2,3,4]
我想找到像所有可能的组合乘法和:
I'm using Python and
I'm given an array like a = [1, 2, 3, 4]
and I want to find sum of all possible combination multiplications like:
有关组合1: 1 + 2 + 3 + 4
有关组合2: 1 * 2 + 2 * 3 + 3 * 4 + 4 * 1
有关的3人组合: 1 * 2 * 3 + 1 * 3 * 4 + 2 * 3 * 4
有关组合4: 1 * 2 * 3 * 4
最后所有这些款项的总和就是我的回答。我使用 numpy.prod()
和 numpy.sum()
。但它仍然太慢。有一些更好的算法来快速找到的总和?
And finally sum of all these sums is my answer. I'm using numpy.prod()
and numpy.sum()
. But it's still too slow. Is there some better algorithm to find the sum quickly?
答
您可以用 numpy的
做和和itertools
from numpy import linspace, prod
from itertools import combinations
arr = np.array([1,2,3,4])
[sum([prod(x) for x in combinations(arr,int(i))]) for i in linspace(1,len(arr), len(arr))]
[10, 35, 50, 24]