1

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.

2
  • How many letters are supposed to be change ? is this random also ? Commented Dec 7, 2017 at 19:22
  • If this is a part of a genetic algorithm and will be repeated many times, consider using a list instead of a string. Commented Dec 7, 2017 at 19:31

4 Answers 4

1

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:]
Sign up to request clarification or add additional context in comments.

2 Comments

hey man, changed index to i aswell, now it works! i love you, can you explain your code a bit? i see that you used list slicing.
@RubenWeijers No, those are slices of the string.
0

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

1 Comment

Maybe use range/slice syntax instead of the explicit loop? virus[:i] + val + virus[1+i:]
0

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)

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.