Itertools to generate scrambled combinations

心已入冬 提交于 2019-11-27 08:26:26

问题


What I want to do is obtain all combinations and all unique permutations of each combination. The combinations with replacement function only gets me so far:

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

My intuition on how to move forward is to do something like this:

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])]

Is there a more efficient algorithm?


回答1:


It sounds like you're thinking of a sort of "permutations with replacement", where an input of 'AB' with a permutation size of 2 would give the outputs

AA
AB
BA
BB

If so, that's the Cartesian product of the input with itself n times. You want itertools.product:

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


来源:https://stackoverflow.com/questions/17912298/itertools-to-generate-scrambled-combinations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!