Python Forum
Replace a list or string element with a random one.. - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Replace a list or string element with a random one.. (/thread-18204.html)



Replace a list or string element with a random one.. - pianistseb - May-09-2019

Hello!

I have to do a very simple task, but I have problems with speed. I have a list called 'chromosome', and I want to replace each N into A,G,C or T at random. I made this code, which is very slow (chromosome in this code is a list):

for i in range(0,len(chromosome)):
    if (chromosome[i] is not ('A' or 'C' or 'G' or 'T')):
        r=rd.randint(1,4)
        if r==1:
            chromosome[i]='A'
        elif r==2:
            chromosome[i]='G'
        elif r==3:
            chromosome[i]='C'
        else:
            chromosome[i]='T'
Can I do something to make it run faster?

Thank you!


RE: Replace a list or string element with a random one.. - buran - May-09-2019

First of all let's fix a bug in your code. You will be surprised to learn that
    if (chromosome[i] is not ('A' or 'C' or 'G' or 'T')):
doesn't do what you expect. see for yourself:

chromosomes = 'NACGT'
for chromosome in chromosomes:
    print(chromosome, chromosome is not ('A' or 'C' or 'G' or 'T'))
Output:
N True A False C True G True T True
so you replace everything that is not A

you have two alternatives
if chromosome == 'N': # replace just N
or
if chromosome not in 'ACGT': # replace everything that is not A, C, G or T
or

if chromosome not in ['A', 'C', 'G', 'T']: # replace everything that is not A, C, G or T
something like this
import random
chromosomes = ['N', 'A', 'C', 'G', 'N', 'T']
new_chromosomes = [random.choice('ACGT') if c == 'N' else c for c in chromosomes]
print(new_chromosomes)
Output:
['A', 'A', 'C', 'G', 'C', 'T']



RE: Replace a list or string element with a random one.. - pianistseb - May-09-2019

Thank you very much for your solution! I didn't put 'if is equal to N' because sometimes in chromosomes you can find also other letters like R or M. Your code is really simple and efficient!


RE: Replace a list or string element with a random one.. - buran - May-09-2019

(May-09-2019, 08:21 AM)pianistseb Wrote: I didn't put 'if is equal to N' because sometimes in chromosomes you can find also other letters like R or M.

do you want to replace these? if you want to replace everything not in ACGT, then use any of the other two example conditions