计算所有乘积组合的 Pythonic 方法

标签 python combinatorics

假设我有一个素数列表 [ 2,3,5 ],我想获得所有 N^3 此类乘积的列表(或迭代器):

pow( 2, 0 ) * pow( 3, 0 ) * pow( 5, 0 ) 
pow( 2, 1 ) * pow( 3, 0 ) * pow( 5, 0 ) 
pow( 2, 0 ) * pow( 3, 1 ) * pow( 5, 0 ) 
pow( 2, 0 ) * pow( 3, 0 ) * pow( 5, 1 ) 
pow( 2, 1 ) * pow( 3, 1 ) * pow( 5, 0 ) 
pow( 2, 0 ) * pow( 3, 1 ) * pow( 5, 1 ) 
pow( 2, 1 ) * pow( 3, 0 ) * pow( 5, 1 ) 
[...]
pow( 2, N-1 ) * pow( 3, N-1 ) * pow( 5, N-1 ) 

Python 的方法是什么? (列表长度为L的情况)

最佳答案

希望我的理解是对的。检查这个(N=3):

from itertools import product
from operators import mul

primes = [2,3,5]
n = 3

sets = product(*[[(i,j) for j in range(n)] for i in primes])
# Now 'sets' contains all the combinations you want. If you just wanted pow(i,j), write i**j instead and skip the map in the next enumeration
# list(sets)
#[((2, 0), (3, 0), (5, 0)), 
# ((2, 0), (3, 0), (5, 1)), 
# ((2, 0), (3, 0), (5, 2)), 
#  ... ... ...
# ((2, 2), (3, 2), (5, 0)), 
# ((2, 2), (3, 2), (5, 1)), 
# ((2, 2), (3, 2), (5, 2))]

productlist = []
for t in sets:
    productlist.append(reduce(mul,map(lambda tp:tp[0]**tp[1],t)))

# now productlist contains the multiplication of each n(=3) items:
#[1, 5, 25, 3, 15, 75, 9, 45, 225, 2, 10, 50, 6, 30, 150, 18, 90, 450, 4, 20, 100, 12, 60, 300, 36, 180, 900]
# pow( 2, 0 ) * pow( 3, 0 ) * pow( 5, 0 ) = 1
# pow( 2, 0 ) * pow( 3, 0 ) * pow( 5, 1 ) = 5
# pow( 2, 0 ) * pow( 3, 0 ) * pow( 5, 2 ) = 25
# .... ... 

或者,单衬可以是:

productlist = [reduce(mul,t) for t in product(*[[i**j for j in range(n)] for i in primes])]

关于计算所有乘积组合的 Pythonic 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18298953/

相关文章:

c++ - -1、+1 的所有组合的 vector 的 vector

Python Numpy 向量化组合学的嵌套 for 循环

python 3 : What is the most efficient way to calculate all permutations of two lists summing to 100?

arrays - 仅使用 3 个元素形成数组的方法有多少?

python - Python 中的更新日期

python - 在此示例中避免使用 iterrows 的好方法是什么?

python - 如何使用 conda 使用 Flask 设置虚拟环境?

python - MongoEngine : ImproperlyConfigured: settings. 数据库配置不正确

python - 启动具有输入参数的另一个脚本的多个实例的脚本

performance - 迭代给定大小的所有子集