python 与 字符串的全排列

评论2,990

问题的引入:

在处理DNA数据的时候,我们可能想枚举n-turple的全部可能形式。

即1-turple的时候,对应 ['A','T','C','G']

而2-turple的时候,对应['AA','AT',...] 等16种。

怎样用程序生成这些turples,哪种效率又最好,这里做个简单的探讨,具体程序如下:

[code lang="python"]
from itertools import product
import time

base=list(‘ATCG’)

def sequence(n):
#x=reduce(lambda x,y:[(a+b) for a in x for b in y],map(lambda

x:[x]*n,[base])[0])
x=reduce(lambda x,y:[(a+b) for a in x for b in y],[base]*8)

def sequence2(n):
if n==1:
return base
elif n>1:
return [temp+temp2 for temp in sequence2(n-1) for temp2 in base]

start=time.time()
sequence(8)
print time.time()-start

start=time.time()
[''.join(x) for x in product(base,repeat=8)]
print time.time()-start

start=time.time()
x=sequence2(8)
print time.time()-start
[/code]

发表评论

匿名网友