计算列表所有组合的乘积

Compute product of all combinations of a list

我有一个包含 11 个数字的列表,我想根据某个规则(2^11 种可能性)测试所有组合的乘积。

我遇到了 this SO question,但它似乎是 return 所有组合的列表,我认为这会占用很多内存。

我的 C++ 想法是遍历每个二进制数 0x0010x7FF 并乘以每个对应位为 1 的数字。

4 个数字的示例:我的列表是 [2, 3, 5, 7]

第一个二进制数是 0001 给出 - 2 = 2

稍后我们会到达 1110 并且产品将是 3 * 5 * 7 = 105

python 中有更好的方法吗?有点操纵似乎不是正确的方法。

使用迭代器的解决方案应该可以在没有内存问题的情况下处理长列表(使用 "functional" 方法)是:

import itertools
from functools import partial
import numpy as np

my_list = [1,3,5,7,9,11,13,15,17,19,21]

# define helper partial function useful to return an iterable of combinations with r elements
combinations_with_r = partial(lambda r: itertools.combinations(my_list, r = r))

# generate all combinations, print them with their products
for r in map(combinations_with_r, range(1, len(my_list) + 1)):
    for j in r:
        print(j, np.prod(j))

您可以声明 my_list = np.array([1,3,5,7,9,11,13,15,17,19,21], dtype = 'int64') 以缓解溢出问题。