How to get sum of products of all combinations in

2019-04-17 17:16发布

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:

For combinations of 1: 1 + 2 + 3 + 4

For combinations of 2:1*2 + 2*3 + 3*4 + 4*1.

For combination of 3: 1*2*3 + 1*3*4 + 2*3*4

For combinations of 4: 1*2*3*4

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?

1条回答
三岁会撩人
2楼-- · 2019-04-17 18:14

You can do with numpy and 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]
查看更多
登录 后发表回答