How to get sum of products of all combinations in an array in Python? [closed]

我的梦境 提交于 2019-12-10 00:35:47

问题


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:


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]


来源:https://stackoverflow.com/questions/32908475/how-to-get-sum-of-products-of-all-combinations-in-an-array-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!