I provide a string and match it with dictionary keys; if the key and string match I print the dictionary values.
def to_rna(dna_input):
dna_rna = {'A':'U', 'C':'G', 'G':'C', 'T':'A'}
rna = []
for key in dna_rna.iterkeys():
if key in dna_input:
rna.append(dna_rna[key])
print "".join(rna)
to_rna("ACGTGGTCTTAA") #the string input
The result should be 'UGCACCAGAAUU' but all I get is 'UGAC'. The problem appears to be that I have duplicate characters in the string and the loop is ignoring this. How do I loop through the dictionary so that it returns the dictionary value as many times as the dict key is found?
If you want to output a character for every character in dna_input
you need to iterate over character in dna_input
. Note that the get()
function provides a default for characters that aren't in your dictionary. I am replacing with nothing, if desired you could put an n
here, or an X.
rna.append(dna_rna.get(char, 'n'))
Your code was only iterating over the 4 entries in the dna_rna
dictionary.
def to_rna(dna_input):
dna_rna = {'A':'U', 'C':'G', 'G':'C', 'T':'A'}
rna = []
for char in dna_input:
rna.append(dna_rna.get(char, ''))
print "".join(rna)
to_rna("ACGTGGTCTTAA") #the string input
However, this isn't the most efficient way to translate a string.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments