DNA sequence not divisible by 3 Python

Viewed 26

I am trying to get the list of codons and aminoacids of the input dna sequence. For this I created a function which verifies if the sequence is divisible by 3 or not. When the function is not divisible by 3 then, I want to get a random codon from the dictionaty, using as precedent the last one or two nucleotides of the sequence and with the random tool get get the final codon.

This is the code that I have so far.


seq = "GAGCGTCTGCTCCGTGTATAAGCCACGTCGGAGCT"
def codons(seq):
    codon_list = []
    for i in range(0, len(seq), 3):
        codon_list.append(seq[i:i+3])
    return codon_list
print("Codons: ")
print (codons(seq))

genetic_code = {
       "GCG" :"A","GCA" :"A","GCT" :"A","GCC" :"A",
       "AGG" :"R","AGA" :"R","CGG" :"R", "CGA" :"R","CGT" :"R","CGC" :"R",
       "AAT" :"N","AAC" :"N",
       "GAT" :"D", "GAC":"D", "TGT" :"C","TGC" :"C",
       "TGA" :"*","TAG" :"*","TAA" :"*", # * Stop codon
       "CAG" :"Q","CAA" :"Q",
       "GAG" :"E","GAA" :"E",
       "GGG" :"G","GGA" :"G","GGT" :"G","GGC" :"G",
       "CAT" :"H","CAC" :"H",
       "ATA" :"I","ATT" :"I","ATC" :"I",
       "TTG" :"L","TTA" :"L","CTG" : "L","CTA" :"L","CTT" :"L","CTC" :"L",
       "AAG" :"K","AAA" :"K",
       "ATG" :"M" , # Start codon
       "TTT" :"F" ,"TTC" :"F" ,
       "CCG" :"P" ,"CCA" :"P" ,"CCT" :"P" ,"CCC" :"P" ,
       "AGT" :"S" ,"AGC" :"S" ,"TCG" :"S" ,"TCA" :"S" ,"TCT" :"S" ,"TCC" :"S" ,
       "ACG" :"T" ,"ACA" :"T" ,"ACT" :"T" ,"ACC" :"T" ,
       "TGG" :"W" ,
       "TAT" :"Y" ,"TAC" :"Y" ,
       "GTG" :"V" ,"GTA" :"V" ,"GTT" :"V" ,"GTC" :"V" 
  }

nn_seq = []
def tranlastion(seq):
    for dna in seq:
        protein_seq = ""
        if len(dna) % 3 != 0:
            for j in range(0, len(dna), 3):
                codon_r = genetic_code[dna[j:j +3]]
                protein_seq += codon_r
            return genetic_code[random.choice(codon_r)]
            
            #print("Choose a random codon")
    for i in range(0, len(dna), 3):
        n_codon = genetic_code[dna[i:i +3]]
        protein_seq += n_codon
        nn_seq.append(protein_seq)
tranlastion(seq)

ISSUE: Once I run the code the output is: KeyError: 'G'

I don't understand where is the error with the key and how could I fix this in order to get the previously mentioned.

Thank you for advices.

0 Answers
Related