Can someone tell me why when I try out this function with this particular example: is_valid_sequence('ABCDEFG'), it comes up "True" instead of "False"? I am completely new to programming in general. This is for an online course I'm taking. Thanks.
def is_valid_sequence(dna_sequence):
''' (str) -> bool
Return True if and only if DNA sequence is made up of 'A', 'T', 'C', and 'G' nucleotides.
>>> is_valid_sequence('ATCGGC')
True
>>> is_valid_sequence('aTcGGc')
False
>>> is_valid_sequence('ABCDEFG')
False
'''
for char in dna_sequence:
if char not in 'ACTG':
return False
else:
return True
6 Answers 6
You are returning too early. Try this
for char in dna_sequence:
if char not in 'ACTG':
return False
return True
or more simply
return all(char in 'ACTG' for char in dna_sequence)
2 Comments
all is perhaps more pythonic.Your method will exit at the first character that matches. Since the first character of ABCDEFG is a valid character, your method return True.
You need to go through the entire string and see if all characters match.
Comments
Because you use return only the first char gets tested.
Simple correction:
res = True
for ch in dna_sequence:
if ch not in 'ACTG':
res &= False # or return as you know it's false
else:
res &= True
return res
But there are more "pythonic" way to do this, take a look at the all() function for example
3 Comments
&= like that? BTW you forgot to return resWhat happens is that as soon as it hits the A, it returns True. Your logic needs to not return until it hits either an invalid character or the end of the string:
for char in dna_sequence:
if char not in 'ACTG':
return False
# we hit the end of the string, so it must be valid
return True
Comments
In your loop, you're returning True if the first value matches, rather than examining all the values. Corrected code:
for char in dna_sequence:
if char not in 'ACTG':
return False
return True
Comments
return causes an exit of the function regardless of anything this will only check one character
for char in dna_sequence:
if char not in 'ACTG':
return False
return true # after whole string checked