如何获得Python中的数组的所有组合的产品总和? [英] How to get sum of products of all combinations in an array in Python?

查看:573
本文介绍了如何获得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]

这篇关于如何获得Python中的数组的所有组合的产品总和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆