生成具有结束条件的随机 RNA 转录本

Generate random RNA transcripts with ending condition

我正在尝试编写一个生成随机 RNA 转录本的程序: 所有 4 个 RNA 核苷酸的概率相等,每个序列以起始密码子开始,仅在引入终止密码子时结束。

import random

def random_rna():
    rna = 'AUG'
    stop_codon = ['UAG','UAA','UGA']
    while rna[-3:] not in stop_codon:
            rna += (random.choice('AUCG'))*3
    return rna

random_rna()

它没有生成序列并且 python 没有出现任何错误...

你的代码进入了一个无限循环,因为 (random.choice('AUCG'))*3 没有按照你的想法去做......见:

In [2]: (random.choice('AUCG')) * 3
Out[2]: 'GGG'

与其调用该函数三次,不如调用一次并将结果一式三份。因此,while 条件永远不会为真。

我建议附加到列表,然后在最后加入一次。它比您进行的所有字符串连接调用都便宜。

stop_codon = ['UAG','UAA','UGA']

def random_rna():
    rna = ['AUG']
    while rna[-1] not in stop_codon:
            rna.append(''.join([random.choice('AUCG') for _ in range(3)]))

    return ''.join(rna)

print(random_rna())
'AUGAGCAGCGAGAGGGGCGCGCAGACGACGCCUGGCUCGUAUAGUUAUAGGACCUUCCGUGAACAUAACGCUACAGUCAGGUUGCAAAAUAAGCAGGUAACUAACUAUCUGCAGGCUCGAGUUGUCCUGCCGUAG'