Ruben Weijers
Ruben Weijers

Reputation: 63

Replace random value in string with random value

virus is supposed to be a string of nucleotides, and the function should return a string consisting of the same amount of nucleotides, but one is changed.

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

so for example if the virus is ATCG it should return something like ATCC or GTCG, how can I go about this, I tried making virus into a list, and replacing a random variable in it with a random of my possible mutations list.

So it should probably make a list from the string virus, do a mutation, put the list back into a string and return the string.

Upvotes: 1

Views: 807

Answers (4)

scharette
scharette

Reputation: 9977

Since string are immutable, I would recommend working with list instead of string. Readability will be increase also in my opinion.

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)

Output

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

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

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

Upvotes: 0

user2390182
user2390182

Reputation: 73470

You can do sth. like the following:

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:]

Upvotes: 1

timko.mate
timko.mate

Reputation: 374

You can do something like this:

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)

Upvotes: 0

Ajax1234
Ajax1234

Reputation: 71451

You can generate a random index to replace at and a random value:

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))

Upvotes: 0

Related Questions