I'm having trouble removing the loop and making it recursion. Can you correct my code?
def translation(dna):
mapping = {"G":"C", "C":"G", "T":"A", "A":"U"}
rna = ""
for char in dna:
rna = mapping[char]
return rna
print(translation())
CodePudding user response:
A possible recursive code is the following
def recursive_translation(dna):
if dna == "":
return ""
mapping = {"G":"C", "C":"G", "T":"A", "A":"U"}
return recursive_translation(dna[:-1]) mapping[dna[-1]]
However, I am quoting a comment from your question since I find it important and want to make sure you see it:
Note that an iterative approach, as your current one, is much more natural than a recursive one. Also, note that recursion depth is limited and that a recursive approach would result in an error with long enough data. – Thierry Lathuille
CodePudding user response:
I agree with the comments made that a recursive approach may not be natural here and also may be slower for large strings. Here are the different ways:
# iterative
def translation(dna):
mapping = {"G":"C", "C":"G", "T":"A", "A":"U"}
rna = ""
for char in dna:
rna = mapping[char]
return rna
print(translation('GCTA'))
# recursive
def translation(dna, mapping = {"G":"C", "C":"G", "T":"A", "A":"U"}):
if len(dna) < 1:
return ''
try:
return mapping[dna[0]] translation(dna[1:])
except KeyError:
raise ValueError(f'The character {dna[0]} is not in translation mapping.')
print(translation('GCTA'))
# perhaps an even better way is to use python's `str.translate()` approach
table = str.maketrans({"G":"C", "C":"G", "T":"A", "A":"U"})
'GCTA'.translate(table)
Note that the ValueError
uses f-strings so this expects you are using python 3.6 or higher. If you are using a lower version you can remove the f-string and it will work.
Out of the three methods I'd probably use the third approach using builtins from python because it is simplest but people may be less familiar with these two string methods.