Trouble completing mRNA function

Viewed 1397

This is the exercise I'm working on:

The function to be built, amino_acids, must return a list of a tuple and an integer when given a string of mRNA code. The first tuple must contain all the amino acids and the integer must be the number of distinct amino acids. You can use the dictionary below to help with your function. The function must also not include the stop codon codes.

This is the code I wrote:

def amino_acids(mrna):
    my_string = " "
    my_dict = {'AUG':'Met', 'CCA':'Pro', 'CCU':'Pro'}

    for i in range(len(mrna)):
        my_string += my_dict[mrna[i]]
# your code here
        return

This is the error I'm getting:

KeyError                                  Traceback (most recent call last)
<ipython-input-42-e85578c5ac05> in <module>
----> 1 amino_acids('AUGCCACCUUGA')

<ipython-input-41-80f9417b4973> in amino_acids(mrna)
      5 
      6     for i in range(len(mrna)):
----> 7         my_string += my_dict[mrna[i]]
      8 # your code here
      9         return

KeyError: 'A'

Would anyone be able to help me with where I went wrong?

1 Answers

Would anyone be able to help me with where I went wrong?

Your loop for i in range(len(mrna)) and subsequent reading of your mRNA in mrna with mrna[i] is looking at single characters. However, you need to look at three characters at once, because each amino acid is encoded as a nucleotide triplet.

I have tried to explain everything that happens in the comments:

def amino_acids(mrna):
    protein = ""  # Start with empty protein string
    translation = {"AUG": "Met", "CCA": "Pro", "CCU": "Pro"}  # Which codon translates for which amino acid
    stop_codons = {"UGA"}  # Define stop codons
    while mrna:  # Repeat loop while mRNA isn't exhausted
        codon = mrna[:3]  # Select first three codes
        mrna = mrna[3:]  # Remove current codon from mRNA
        if codon in stop_codons:
            break  # Break loop if triple is a stop codon
        amino_acid = translation[codon]  # Translate codon into its amino acid
        protein += amino_acid  # Add the amino acid to the protein string
    return protein

print(amino_acids("AUGCCACCUUGA"))

Which prints:

MetProPro
Related