5

我正在尝试使用随机数和随机字符串在 python 中生成随机 DNA 序列。但我只得到一个字符串作为我的输出。例如:如果我给出长度为 5 (String(5)) 的 DNA,我应该得到一个输出“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
4

5 回答 5

10

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

import random

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

print DNA(5)
于 2014-01-18T15:14:27.610 回答
7

你回来得太快了:

from random import choice
def String(length):

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

如果您的return语句在for循环内,您将只迭代一次 --- 您将使用return.

来自关于语句的Python 文档return:“ return 将当前函数调用与表达式列表(或 None)作为返回值。”

所以,把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)])

于 2014-01-18T15:07:58.493 回答
0

我已经升级了代码以提供从 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)
于 2014-08-29T05:37:14.183 回答
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)
于 2019-10-09T08:47:32.647 回答
0

由于矢量化,也许 numpy 工作得更快?:

import numpy as np
seq_length = 100
my_seq = ''.join(np.random.choice(('C','G','T','A'), seq_length ))
于 2021-06-28T15:57:22.583 回答