0

Am learning python and one of the questions in our study guide asks to evaluate RNA sequences. I do not get the expected outputs as suggested by the question, I get 17.

Here is the code:

####START FUNCTION
def rna_length(mrna);
start_rna = 'AUG';

end_rna1 = 'UGA';
end_rna2 = 'UAA';
end_rna3 = 'UAG';

if (mrna[0:3]==start_rna) and (mrna [-3:]==end_rna1 or end_rna2 or end_rna3):
length = len(mrna[3:-3])
return length
else: ((mrna[0:3]!=start_rna) or (mrna [-3:]!=end_rna1 or end_rna2 or end_rna3))
return "Not readable RNA code"

####END FUNCTION

A link to a screenshot of the question here

  • Does this answer your question? [Why does `a == x or y or z` always evaluate to True?](https://stackoverflow.com/q/20002503/6045800) – Tomerikoo Aug 24 '21 at 14:28

1 Answers1

0

The issue is you using the boolean operator or to compare strings. You can think of the comparisons like this:

(mrna [-3:]==end_rna1 or end_rna2 or end_rna3)
(((mrna [-3:]==end_rna1) or end_rna2) or end_rna3)

Because or is a boolean operator, it needs to work on booleans. You can convert strings to booleans using bool(<str>)

(((mrna [-3:]==end_rna1) or bool(end_rna2)) or bool(end_rna3))

Any string that is not empty (ie. any string that is not "") is "truthy." What that means is that bool(non_empty_str) == True and bool('') == False.

(((mrna [-3:]==end_rna1) or True) or True)
((True) or True)
(True or True)
True

Now, how should you fix it? There are a few approaches to this.

  1. Properly use or.

     if (mrna[0:3]==start_rna) and (mrna[-3:]==end_rna1 or mrna[-3:]==end_rna2 or mrna[-3:]==end_rna3):
         length = len(mrna[3:-3])
         return length
     else:
         ((mrna[0:3]!=start_rna) or (mrna[-3:]!=end_rna1 or mrna[-3:]!=end_rna2 or mrna[-3:]!=end_rna3))
         return "Not readable RNA code"
    
  2. Use a collection. Note that it is standard to use tuples instead of lists whenever you don't want to modify the collection. I used lists here because the brackets look different. You can also use sets for quicker in, but that's overkill for 3.

     if mrna[0:3] == start_rna and mrna[-3:] in [end_rna1, end_rna2, end_rna3]:
         length = len(mrna[3:-3])
         return length
     else:
         (mrna[0:3] != start_rna or mrna[-3:] not in [end_rna1, end_rna2, end_rna3])
         return "Not readable RNA code"
    

Heck, you can even use the string methods str.startswith and str.endswith.

    if mrna.startswith(start_rna) and mrna.endswith([end_rna1, end_rna2, end_rna3]):
        length = len(mrna[3:-3])
        return length
    else:
        ...
HelixAchaos
  • 131
  • 1
  • 3