2013-07-28 103 views
1

我想要做的是獲得每個組合的所有組合和所有獨特的排列。與替換功能的組合,唯一讓我至今:Itertools生成混合組合

from itertools import combinations_with_replacement as cwr 
foo = list(cwr('ACGT', n)) ## n is an integer 

我就如何推進直覺是做這樣的事情:

import numpy as np 
from itertools import permutations as perm 
bar = [] 
for x in foo: 
    carp = list(perm(x)) 
    for i in range(len(carp)): 
     for j in range(i+1,len(carp)): 
      if carp[i] == carp[j]: 
       carp[j] = '' 
    carp = carp[list(np.where(np.array(carp) != '')[0])] 
    for y in carp: 
     bar.append(y) 
for i in range(len(bar)): 
    for j in range(i+1,len(bar)): 
     if bar[i] == bar[j]: 
      bar[j] = '' 
bar = [bar[x2] for x2 in list(np.where(np.array(bar) != '')[0])] 

有沒有更有效的算法?

回答

4

這聽起來像你想一種「與替代置換」,其中的'AB'爲2的置換大小的輸入將使輸出

AA 
AB 
BA 
BB 

如果是這樣的,這是的Cartesian product輸入本身n次。你想要itertools.product

>>> import itertools 
>>> list(itertools.product('AB', repeat=2)) 
[('A', 'A'), ('A', 'B'), ('B', 'A'), ('B', 'B')]