Wednesday, 1 June 2016

Complementing a Strand of DNA

In the third Rosalind problem we are asked to return the reverse complement of a DNA strand. As with the previous problems I started the program by defining an empty string and opening the file containing the data. The program then appends the complement of each nucleotide to the empty string that was defined in the beginning.

So far the problem was quite simple but then it came to reversing the string. I haven't reversed a sting before so i googled it and found a thread about it at Stack Overflow. There seems to be many different ways in which to do this, but the most popular one was to use extended slices as this is a very fast way to do this. This solution resulted in the following code:


trans = ''                             
with open('sampledata.txt') as f:      
    for line in f:                     
        for nt in line:                
            if nt == 'A':              
                trans+='T'             
            elif nt == 'C':            
                trans+='G'             
            elif nt == 'T':            
                trans+='A'             
            elif nt == 'G':            
                trans+='C'             
reverse = trans[::-1]                  
with open('compdna.txt','w') as answer:
    answer.write(reverse)              


No comments:

Post a Comment