Jose Ortiz
Jose Ortiz

Reputation: 21

Why does this function return the wrong results?

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

Upvotes: 2

Views: 307

Answers (6)

user180100
user180100

Reputation:

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

Upvotes: 2

Joran Beasley
Joran Beasley

Reputation: 113930

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 

Upvotes: 0

Jeffrey Bauer
Jeffrey Bauer

Reputation: 14080

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

Upvotes: 0

Burhan Khalid
Burhan Khalid

Reputation: 174614

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.

Upvotes: 3

Gabe
Gabe

Reputation: 86698

What 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

Upvotes: 1

John La Rooy
John La Rooy

Reputation: 304127

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)

Upvotes: 11

Related Questions