I am given a string and have to return False if there is one or more invalid characters, otherwise True. The caveat is that I can only built-in functions and str operations
As others have said, your recursive function does not return when it hits the end of the recursion. You can say something like:
if len(dna) == 1 and dna in ['A','T','G','C']:
return True
That is, if you know your dna
string is always greater than or equal to one in length. All together you might end up with something like:
def is_vaild_sequence(dna):
if dna[0] not in ['A','T','G','C']:
return False
if len(dna) == 1:
return True
return is_vaild_sequence(dna[1:])
Here, the first check determines if the dna
's first character is valid, followed by the recursive structure to check the whole sequence.
Ideally, if this can be solved without the constraint of recursion, take it. An iterative approach is far better i.e.
for i in range(0,len(dna)):
if dna[i] not in ['A','T','G','C']:
return False
return True