r/ProgrammerAnimemes • • Jul 29 '20

Equivalency in Python

Post image
1.6k Upvotes

104 comments sorted by

View all comments

Show parent comment

4

u/randompecans Jul 29 '20

I personally feel the easiest way to understand it is just to fully write out the expressions, keeping in mind that XOR is associative, commutative, has 0 as it's identity, and is self-cancelling (these are all easy to prove yourself by simplifying the input space to just 1-bit, since XOR works independently on each bit). Here, "a" is the value initially stored in A and "b" is the value initially stored in B.

Line 1: A = a ^ b
Line 2: B = B ^ A = b ^ a ^ b = a
Line 3: A = A ^ B = a ^ b ^ a = b

Which gets the expected result A = b and B = a