生成DNA序列,不包括特定序列

3
我刚开始学习使用Python编程。在课堂上,我们被要求生成一个随机的DNA序列,该序列不包含特定的6个字母序列(AACGTT)。目标是创建一个函数,始终返回合法的序列。目前我的函数大约78%的时间可以生成正确的序列。如何让它100%返回合法序列?任何帮助都将不胜感激。
以下是我现在的代码:
from random import choice
def generate_seq(length, enzyme):
    list_dna = []
    nucleotides = ["A", "C", "T", "G"]
    i = 0
    while i < 1000:
        nucleotide = choice(nucleotides)
        list_dna.append(nucleotide)
        i = i + 1

    dna = ''.join(str(nucleotide) for nucleotide in list_dna)
    return(dna) 


seq = generate_seq(1000, "AACGTT")
if len(seq) == 1000 and seq.count("AACGTT") == 0:
    print(seq)

1
在你的22%不合法的情况中,是什么使得数据不合法? - JacobIRR
1
如果唯一的目标是获得一个不包含这个6字母序列的DNA序列,只需更改“nucleotides = [“A”]”即可达到技术上的正确(最好的正确)。如果你生成了该序列,也可以直接将其删除。或者你可以用不同的方式进行限制。这取决于你以后想要对这个序列做什么。 - CJR
你的DNA序列可以合法地包含AACGT,但是为了保持合法性,下一个基因应该只从[A,C,G]中选择,因为T是不允许的。 - rossum
2个回答

1
一种选择是检查循环中最后几个条目,只有在没有创建“坏”序列时才继续添加。然而,这可能会导致出现“AACGT”序列的概率高于真正随机,只是最后一个字母不同。
from random import choice
def generate_seq(length, enzyme):
    list_dna = []
    nucleotides = ["A", "C", "T", "G"]
    i = 0
    while i < 1000:
        nucleotide = choice(nucleotides)
        list_dna.append(nucleotide)
        #check for invalid sequence. If found, remove last element and redraw
        if ''.join(list_dna[-6:]) == "AACGTT":
            list_dna.pop()
        else:
            i = i + 1

    dna = ''.join(str(nucleotide) for nucleotide in list_dna)
    return(dna) 


seq = generate_seq(1000, "AACGTT")
if len(seq) == 1000 and seq.count("AACGTT") == 0:
    print(seq)

1

一个想法是检查前5个核苷酸是否等于AACGT,在这种情况下只从["A", "C", "G"]中选择。

from random import choice


def generate_seq(length, enzyme, bad_prefix="AACGT"):
    list_dna = []
    nucleotides = ["A", "C", "T", "G"]
    i = 0
    while i < 1000:
        if list_dna[-5:] != bad_prefix:
            nucleotide = choice(nucleotides)
        else:
            nucleotide = choice(["A", "C", "G"])
        list_dna.append(nucleotide)
        i = i + 1

    dna = ''.join(str(nucleotide) for nucleotide in list_dna)
    return dna


seq = generate_seq(1000, "AACGTT")
if len(seq) == 1000 and seq.count("AACGTT") == 0:
    print(seq)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接