python求数组的所有组合,如何获得Python中的数组的所有组合的产品总和?

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?

解决方案

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]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值