[英]How to find the largest sum of the subset from a giving array. (Subset can't not have element greater than sum of any 2 elements)
[英]Find product of any subset of elements from a list
從列表中查找任意數量元素的乘積的最佳方法是什么?
例如,如果我有[a,b,c]
作為輸入,我應該得到[a,b,c,a*b,a*c,b*c,a*b*c]
作為輸出(元素的順序)輸出無關緊要。)
PS:我們可以遞歸執行嗎? (例如,您只需要a*b
和c
的乘積即可得到a*b*c
的乘積。
任何想法或建議都歡迎。 提前致謝!
干得好:
from itertools import combinations
l = [2, 3, 5]
result = []
for i in range(1, len(l) + 1):
result += list(combinations(l, i))
multiplied_result = [reduce(lambda x, y: x*y, lst) for lst in result]
現在,如果我們打印結果,我們得到
>>> print listmap
[2, 3, 5, 6, 10, 15, 30]
您可以在列表itertools.combinations
中使用itertools.combinations
:
>>> def find_mul(li):
... return [[reduce(lambda x,y:x*y,j) for j in combinations(li,i)] for i in xrange(2,len(li)+1)]
...
演示:
>>> [list(combinations([2,3,4],i)) for i in xrange(2,len([2,3,4])+1)]
[[(2, 3), (2, 4), (3, 4)], [(2, 3, 4)]]
>>> l=[2,3,4]
>>> find_mul(l)
[[6, 8, 12], [24]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.