The Case of the Mystery Operator
Inspired partially by xkcd and partially by testimony from other programmers, I've decided to take up learning Python in my spare time. I've been using the free e-book Dive Into Python as a reference, and it's been an interesting experience so far (whitespace for code blocks!?)
I was showing the Python Shell to my friend Thomas the other day, and he typed in a few equations to try it out. While "2+2" and "3*8" resolved normally, "2^3", which is a standard notation for two raised to the third power, returned "1". We were a bit confused, but decided that the caret symbol "^" must mean something else in Python. We entered a few more formulas in an attempt to discover what the symbol meant, and here are the results:
- 1^0 = 1
- 1^2 = 3
- 2^0 = 2
- 2^2 = 0
- 2^3 = 1
- 3^2 = 1
- 3^4 = 7
- 4^1 = 5
Try as we might, we just couldn't figure out what this operator did. I had a theory that it had something to do with modular arithmetic, but some cases just didn't fit. Despite our combined brain power, we just couldn't crack it, and after twenty minutes consented to Googling it.
I would challenge you to try and figure it out yourself! For cheaters, the answer is below.
In Python, two multiplication symbols "**" are used to indicate exponents, while the caret symbol in this context is used to indicate XOR (exclusive or). Since I was comparing two integers, the computer was doing bitwise XOR on the two numbers and returning the result as an integer. For instance:2 = 010 (binary), 3 = 011 (binary), 010 XOR 011 = 001 = 1
3 = 011 (binary), 4 = 100 (binary), 011 XOR 100 = 111 = 7
It was obvious in retrospect, but my mind was so focused on the usual mathematical operators that I hadn't even considered the basic computer operations. However, as it is with most lessons learned the hard way, I'll remember for the rest of my life how to do an exclusive or in Python.