生成DNA的随机序列

Rac*_*hel 4 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
Run Code Online (Sandbox Code Playgroud)

Pau*_*kin 8

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

import random

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

print DNA(5)
Run Code Online (Sandbox Code Playgroud)


Rus*_*hal 5

你回来太快了:

from random import choice
def String(length):

   DNA=""
   for count in range(length):
      DNA+=choice("CGTA")
      return DNA
Run Code Online (Sandbox Code Playgroud)

如果你的return语句在for循环中,你将只迭代一次---你将退出函数return.

Python Documentation on return语句:" return将当前函数调用与表达式列表(或None)一起作为返回值."

所以,把return你的功能放在最后:

def String(length):

       DNA=""
       for count in range(length):
          DNA+=choice("CGTA")
       return DNA
Run Code Online (Sandbox Code Playgroud)

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

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

然后,你想要weightedchoice而不是choice在你的循环中调用:

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