Most people learn to code because they want to build something. Not everyone is interested in the theory behind why the code works. But having a solid understanding of computer science topics can help you write better code.
The following problem reminded me of the gaps in my understanding of discrete math.
The Problem
We have two monkeys, a and b, and the parameters a_smile and b_smile indicate if each is smiling. We are in trouble if they are both smiling or if neither of them is smiling. Return True if we are in trouble.
The Easy Way
The first solution I thought of involved wrapping each pair in parentheses to ensure that they would be evaluated first. But I wondered if they were really necessary. I ran the tests without them and they all passed.
def monkey_trouble(a_smile, b_smile):
# return (a_smile and b_smile) or (not a_smile and not b_smile)
return a_smile and b_smile or not a_smile and not b_smileI wanted to know why this worked, so I asked Claude about the order of operations for Boolean operators. It explained that the operators are evaluated from specific to general: not, and, then or. All the nots were evaluated first, then the and pairings and lastly the or.
The Confusing Way
Claude also showed me a solution I hadn’t thought of. If you read the problem carefully, you’ll notice that a_smile and b_smile must match to return True. So a double equals comparison would also work.
def monkey_trouble(a_smile, b_smile):
return a_smile == b_smileDo You Need a CS Degree?
You don’t need a computer science degree to write code. But understanding how things work can make your code much simpler and sometimes more efficient. Those computer science concepts become tools you can use to solve problems.