python - 寻找优雅的球形 DNA 字符串扩展

标签 python permutation glob dna-sequence

我正在尝试对一组具有多个可能碱基的 DNA 字符串进行类似球形的扩展。

我的 DNA 字符串的基础包含字母 A、C、G 和 T。但是,我可以有特殊字符,例如 M,它可以是 A 或 C。

例如,假设我有字符串:

ATMM

我想将此字符串作为输入并输出四个可能的匹配字符串:

ATAA ATAC ATCA ATCC

我觉得必须有一些优雅的 Python/Perl/正则表达式技巧来做到这一点,而不是暴力解决方案。

感谢您的建议。

编辑,感谢cortex的产品运算符(operator)。这是我的解决方案:

仍然是 Python 新手,所以我打赌有比另一个 for 循环更好的方法来处理每个字典键。任何建议都会很棒。

import sys
from itertools import product

baseDict = dict(M=['A','C'],R=['A','G'],W=['A','T'],S=['C','G'],
                  Y=['C','T'],K=['G','T'],V=['A','C','G'],
                  H=['A','C','T'],D=['A','G','T'],B=['C','G','T'])
def glob(str):
    strings = [str]

    ## this loop visits very possible base in the dictionary
    ## probably a cleaner way to do it
    for base in baseDict:
        oldstrings = strings
        strings = []
        for string in oldstrings:
            strings += map("".join,product(*[baseDict[base] if x == base 
                                 else [x] for x in string]))
    return strings

for line in sys.stdin.readlines():
    line = line.rstrip('\n')
    permutations = glob(line)
    for x in permutations:
        print x

最佳答案

同意其他发帖者的观点,这似乎是一件奇怪的事情。当然,如果你真的想这样做,(一如既往)有一种优雅的方法可以在 Python (2.6+) 中实现:

from itertools import product
map("".join, product(*[['A', 'C'] if x == "M" else [x] for x in "GMTTMCA"]))

具有输入处理的完整解决方案:

import sys
from itertools import product

base_globs = {"M":['A','C'], "R":['A','G'], "W":['A','T'],
              "S":['C','G'], "Y":['C','T'], "K":['G','T'],

              "V":['A','C','G'], "H":['A','C','T'],
              "D":['A','G','T'], "B":['C','G','T'],
              }

def base_glob(glob_sequence):
    production_sequence = [base_globs.get(base, [base]) for base in glob_sequence]
    return map("".join, product(*production_sequence))

for line in sys.stdin.readlines():
    productions = base_glob(line.strip())
    print "\n".join(productions)

关于python - 寻找优雅的球形 DNA 字符串扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1098461/

相关文章:

python - 使用 ConfigParser Python 更改 ini 文件中的值

python - 使用 python 编程时在迭代时修改列表

python - tf.keras 中的 A2C 算法 : actor loss function

c++ - 字符串算法分析的排列

运算符和操作数排列的算法

php——仅用于搜索目录和 .jpg 的 glob

python - 在 glob.glob() 中排除两个目录

python - 我想在给定的虚拟函数中更新我的函数 interpolate()

algorithm - n×n零矩阵用1和-1填充的方法使得每行每列只能有一个1和-1,每行每列之和为0

java - Spring Reactive Router Path - 带排除的通配符