What is an example of the not boolean?

what is the purpose of “not” boolean?

How would you code: If any character in the string s is something other that “A”, “C”, “T”, or “G”, return False; otherwise return True.

s = "ACCTGCCCQTTTTA .... 1 million characters.... AT"

There are probably dozens of ways to code it. Here’s one

def find_bad_char(s):
    for ch in s:
        if not ch in "ACGT":
            return False
    return True
23 Likes

In this case, what is ‘ch’? Also, I see that you’re very active in this, Patrick. Hats off to ya!

6 Likes

I’ll take a crack at explaining for you.

In this case, ‘ch’ is referring to the characters in the string. He is using a “for loop” to iterate through each character in the string to check if it matches any of the characters “A”, “C”, “T”, or “G”.

‘ch’ is the variable Patrick assigned in the for loop to hold the temporary value of the character in the string he is iterating over.

8 Likes

What is the difference between if not ch in “ACGT”: vs if ch not in “ACGT”:"

def find_bad_char(s):
for ch in s:
if not ch in “ACGT”:
return False
return True

def find_bad_char(s):
for ch in s:
if ch not in “ACGT”:
return False
return True

1 Like

In terms of how they work, they are both functionally the same. The use of ‘not in’ is preferred according to PEP-8 because it is easier to read; it’s more like a real English sentence.

6 Likes

i thought this was cool to see:

if not (credits >=120 or gpa >=2.0):

is the same as

if not credits >=120 and not gpa >=2.0:

4 Likes

This is a little (only slightly) like the birthday paradox. Finding a solution can go the long way or the short way. The short way doesn’t come intuitively to a lot of people, just like this problem is often only looked at from one perspective that leads to the long way to solve it.

How about we eliminate every student whose grade point average is below 2. They are an automatic fail, so out they go. That leaves only students with a GPA of 2 or greater (a passing grade). The only thing keeping them from going on to college is whether or not they have enough credits. If not, then we talk with them to make plans to pick up the extra credits during the summer.

Barring either of the conditions above, the only thing left is, off to college. The logic is straight forward and doesn’t need any and or or operations. Turns out to be the short way.

Eg
# given c and g parameters
if g < 2:
  return 'See you next term.'
if c < 120:
  return 'Not enough credits. Enroll in summer class.'
return 'You are off to college!'

Aside

Be warned… Logical operations can be crippling if we get them wrong or base them upon unproven assertions (and/or assumptions). This is a minefield. Just be absolutely certain that there is no special case that will thwart the logic and lead to a false positive or a false negative. Just saying.

2 Likes

This is simple, but I needed it. Thanks for sharing!