我有一个跟随字符串 - “AACCGGTTT”(字母是[“A”,“G”,“C”,“T”])。我想在任意两个位置生成与原始字符串不同的所有字符串,即
GAGCGGTTT
^ ^
TATCGGTTT
^ ^
我怎样才能用Python做到这一点?
我只有蛮力解决方案(它正在运行):
生成给定字母表中长度相同的所有字符串
追加与给定字符串有两个不匹配的字符串
但是,您能否提出更有效的方法呢?
答案 0 :(得分:4)
我可能会使用itertools。也许像是
from itertools import combinations, product
def generate(s, d=2):
N = len(s)
letters = 'ACGT'
pool = list(s)
for indices in combinations(range(N), d):
for replacements in product(letters, repeat=d):
skip = False
for i, a in zip(indices, replacements):
if pool[i] == a: skip = True
if skip: continue
keys = dict(zip(indices, replacements))
yield ''.join([pool[i] if i not in indices else keys[i]
for i in range(N)])
然后只是
list(generate("AACCGGTTT"))