在范围(i,j)之间生成核苷酸k聚体的所有组合

时间:2016-03-17 05:17:37

标签: python combinations permutation bioinformatics itertools

我需要生成一个长度在5-15之间的所有可能核苷酸组合的列表。

nucleotides = ['A', 'T', 'G', 'C']

预期结果:

AAAAA
AAAAT
AAAAC
AAAAG
AAATA
AAATT
...
AAAAAAAAAAAAAAA
AAAAAAAAAAAAAAT
etc.

我试过了:

for i in range(5,16):
    for j in itertools.permutations(nucleotides, i):
        print j

但如果len(nucleotides) < i,这不起作用。

提前致谢!

3 个答案:

答案 0 :(得分:4)

如果您想查找所有组合,则应使用.product(),因为.permutations()无论如何都不会产生重复的核苷酸,如AAAAAAATGC。试试这个:

for i in range(5, 16):
    combinations = itertools.product(*itertools.repeat(nucleotides, i))
    for j in combinations:
        print(j)

更新:正如@JaredGoguen所提到的,repeat参数也可以在这里使用:

combinations = itertools.product(nucleotides, repeat=i)

答案 1 :(得分:2)

您可以生成的另一种方法是使用允许重复的combinations_with_replacement()

import itertools

result=set()
nucleotides = ['A', 'T', 'G', 'C']
for i in range(5,16):
    for j in itertools.combinations_with_replacement(nucleotides, i):
        print(''.join(j))

然后您可以进一步置换它们以获得所有这些变体:

import itertools

result=set()
nucleotides = ['A', 'T', 'G', 'C']
for i in range(5,16):
    for j in itertools.combinations_with_replacement(nucleotides, i):
        for k in itertools.permutations(j):
            result.add(''.join(k))
for i in result:
    print(i)

答案 2 :(得分:2)

为了增加塞尔丘克的答案,这里有一个产生可迭代的单行。

from itertools import chain, product

chain(product(nucleotides, repeat=i) for i in range(5, 16))