How do I convert this iterative function to a recursive one?

This function map input strings to that in a dictionary, outputting the result. Any idea how this can be approached recursively?

def dna(seq):
    hashtable = {'A': 'U', 'G': 'C', 'T': 'A', 'C': 'G'}
    ans = ''
    for i in range(len(seq)):
        ans += hashtable[seq[i]]
    return ans


print(dna('AGCTGACGTA'))

Thanks.

Answer

You should understand recursion is not always the answer.

There is a maximum recursion depth in python which you can change. But still you will have a limit. See: https://stackoverflow.com/a/3323013/2681662

The maximum recursion depth allowed:

import sys
print(sys.getrecursionlimit())

So iterative approach is better in your case.

Still let’s see how the recursive version would look like.

For a recursive function you have to follow simple rules:

  1. Create an exit condition
  2. Call yourself (the function) again.
def dna_r(seq):
    hashy = {'A': 'U', 'G': 'C', 'T': 'A', 'C': 'G'}
    if len(seq) == 1:
        return hashy[seq]

    return dna_r(seq[0]) + dna_r(seq[1:])