用随机值替换字符串中的随机值

时间:2017-12-07 19:20:13

标签: python string python-3.x list random

病毒应该是一串核苷酸,并且该函数应该返回由相同数量的核苷酸组成的字符串,但是其中一个被更改。

def mutate(virus):
    mutations = ['A', 'T', 'C', 'G']
    virus.split
    random.randrange(1, stop=len(virus), step=1) = random.choice(mutations)

所以例如,如果病毒是ATCG,它应该返回类似ATCC或GTCG的东西,我该如何解决这个问题,我尝试将病毒列入一个列表,并用随机的可能突变列表替换其中的随机变量

所以它应该从字符串病毒中创建一个列表,做一个变异,将列表放回一个字符串并返回字符串。

4 个答案:

答案 0 :(得分:1)

你可以做某事。如下:

def mutate(virus):
    # choose random index to change
    index = random.randint(0, len(virus) - 1)

    # make sure you are not using the previous char by removing it from 
    # the mutations to choose from
    mutations = [c for c in 'ATCG' if c != virus[index]]

    # swap out the char at index with a random mutation
    return virus[:index] + random.choice(mutations) + virus[index+1:]

答案 1 :(得分:0)

您可以生成随机索引来替换at和随机值:

import random
def mutate(virus):
   mutations = ['A', 'T', 'C', 'G']
   i = random.randint(0, len(virus)-1)
   val = random.choice(mutations)
   return ''.join(val if c == i else a for c, a in enumerate(virus))

答案 2 :(得分:0)

您可以这样做:

import random
def mutate(virus):
    mutations = ['A', 'T', 'C', 'G']
    r = random.randint(0, len(virus)-1)
    virus = list(virus)
    virus[r] = random.choice(mutations)
    return ''.join(virus)

答案 3 :(得分:0)

由于字符串是不可变的,我建议使用list而不是string。在我看来,可读性也会提高。

import random
def mutate(virus):
    mutations = ['A', 'T', 'C', 'G']
    virus = list(virus)
    virus[random.randint(0, len(virus)-1)] = random.choice(mutations)
    return "".join(virus)

<强>输出

>>> print(mutate('ATCG'))
ATCT

>>> print(mutate('ATCG'))
ATTG

>>> print(mutate('ATCG'))
ATCC