sp_k_mxs
sp_k_mxs

Reputation: 27

Use a dictionary to provide the mapping of DNA to RNA bases

I wrote this code in order to answer the topic 8 question 5 in pyschools learning process. The code is working but I believe that there is a more elegant way to take the same result, but as a novice not only in python but also in programming I can't think anything. Can anybody to help?

# Use a dictionary to provide the mapping of DNA to RNA bases.
def mRNAtranscription(dna_template):
    dna2rna = { }
    mrna = ''
    l = []
    for base in dna_template: 
        dna2rna =  {'A':'U', 'T':'A', 'C':'G', 'G':'C'}
        mrna = dna2rna.get(base)
        l.append(mrna)
    return ''.join(l)

Upvotes: 0

Views: 1662

Answers (2)

Raman Shah
Raman Shah

Reputation: 497

Your code is not bad but also not terribly idiomatic. A list comprehension is a good way to go:

dna2rna = {'A':'U', 'T':'A', 'C':'G', 'G':'C'}
rna = ''.join([ dna2rna[base] for base in dna_template])

By the way, as a point of hygiene, try to avoid sticking a definition of a constant (like your dna2rna) inside of a loop...it just costs processing time in there!

Upvotes: 1

koffein
koffein

Reputation: 1882

I assume dna_template is a string and I think this is the way to go if you do not want to dive in special modules.

def func(dna_template):
    dna2rna =  {'A':'U', 'T':'A', 'C':'G', 'G':'C'}
    # take every base and translate it to rna and join all rna-bases to a string
    return ''.join(dna2rna.get(base) for base in dna_template)

func('ATCG')

Out:'UAGC'

Upvotes: 2

Related Questions