发现元素的任意子集的产物从列表 [英] Find product of any subset of elements from a list

查看:114
本文介绍了发现元素的任意子集的产物从列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是找到任何数量元素的产品从列表中的最佳方法是什么?

what is the best way to find the product of any number of elements from a list?

例如,如果我有 [A,B,C] 作为输入,我应该得到 [A,B,C,A * B ,A * C,B * C,A * B * C] 作为输出(顺序输出并不重要元素。)

e.g if I have [a,b,c] as the input, i should get [a,b,c,a*b,a*c,b*c,a*b*c] as the output (order of elements for output doesn't matter.)

PS:我们能做到这一点递归? (例如,你只需要 A * B C ,以获得产品 A的产品* B * C

PS: Can we do it recursively? (e.g you just need the product of a*b and c to get the product a*b*c.

任何想法或建议,欢迎。在此先感谢!

Any idea or suggestion is welcome. Thanks in advance!

推荐答案

在这里你去:

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]

现在,如果我们打印结果,我们得到

Now if we print the result, we get

>>> print listmap
[2, 3, 5, 6, 10, 15, 30]

这篇关于发现元素的任意子集的产物从列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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