2013-08-18 55 views
2

說我有一個素數列表[2,3,5],我想獲得所有N^3這樣的產品的列表(或迭代器):Pythonic方式來計算產品的所有組合

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) 

什麼是pythonic方式做到這一點? (在列表長度爲L的情況下)

+1

http://docs.python.org/2/library/itertools.html#itertools.combinations會派上用場 – msw

+0

是否必須按此順序? –

回答

1

我希望我能幫到你。檢查此(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])] 
1

這應該做到這一點:

from itertools import product 
from operator import mul 

def all_products(l, k): 
    for t in product(*[[(p, e) for e in range(k)] for p in l]): 
     yield reduce(mul, [x[0] ** x[1] for x in t], 1) 

的關鍵是使用itertools.product

用法:

for prod in all_products([2, 3, 5], 3): 
    print prod 

這會給你的形式2^a0 * 3^a1 * 5^a2其中0 <= aj < 3的所有產品。