生成DNA的随机序列

时间:2014-01-18 15:06:21

标签: python dna-sequence

我试图使用随机数和随机字符串在python中生成随机DNA序列。但我只得到一个字符串作为我的输出。例如:如果我给出长度为5的DNA(String(5)),我应该得到一个输出“CTGAT”。同样,如果我给String(4)它应该给我“CTGT”。但我得到“G”或“C”或“T”或“A”;即每次只有一个字符串。谁有人可以帮我这个?

我尝试了以下代码:

from random import choice
def String(length):

   DNA=""
   for count in range(length):
      DNA+=choice("CGTA")
      return DNA

5 个答案:

答案 0 :(得分:8)

我一次性生成字符串,而不是构建它。除非Python聪明并优化字符串添加,否则它会将运行时复杂性从二次变为线性。

import random

def DNA(length):
    return ''.join(random.choice('CGTA') for _ in xrange(length))

print DNA(5)

答案 1 :(得分:5)

你回来太快了:

from random import choice
def String(length):

   DNA=""
   for count in range(length):
      DNA+=choice("CGTA")
      return DNA

如果您的return语句位于for循环内,则只会迭代一次 - 您将使用return退出该函数。

来自Python Documentation on return statements: “ return将当前函数调用与表达式列表(或无)一起作为返回值。”

所以,将return放在函数的末尾:

def String(length):

       DNA=""
       for count in range(length):
          DNA+=choice("CGTA")
       return DNA

编辑:这是一个加权选择方法(它只适用于当前的字符串,因为它使用字符串重复)。

def weightedchoice(items): # this doesn't require the numbers to add up to 100
    return choice("".join(x * y for x, y in items))

然后,您想在循环中调用weightedchoice而不是choice

DNA+=weightedchoice([("C", 10], ("G", 20), ("A", 40"), ("T", 30)])

答案 2 :(得分:1)

我已升级代码以提供从0到100%的GC百分比分配。上面的代码总是产生50%的分布。

actg_distribution字符串可以是已知GC百分比的现有DNA序列的任何长度。某个范围的GC百分比是常见的用例。


import random

# Return random CGTA sequences, set minimum = maximum to get a specified length.
def random_length_dnasequence(minimum=25, maximum=10000, actg_distribution=None):
    if (minimum == maximum):
        length = minimum
    else:
        length = random.randint(minimum, maximum)
    if (actg_distribution == None):
        actg_distribution = ''.join(random.choice('cgta') for _x in xrange(7))

    return ''.join(random.choice(actg_distribution) for _x in xrange(length))


def random_dnasequence(length, actg_distribution=None):
    return random_length_dnasequence(length, length, actg_distribution)

答案 3 :(得分:0)

使用random.choices的python 3.6快速功能

import random

def string(length=int(), letters="CGTA"):
        #slower 0.05s for 20000 nt
#     dna =""
#     for count in range(length):
#         dna+=choice("CGTA")
#     return dna

    #0.013s for 20000 nt
    return''.join(random.choices(letters, k=length)

答案 4 :(得分:0)

也许由于矢量化,numpy 的工作速度更快了?:

import numpy as np
seq_length = 100
my_seq = ''.join(np.random.choice(('C','G','T','A'), seq_length ))
相关问题