Title: Stupid code trick: Use xor to switch two values in Python
Back in olden times, memory was expensive and programmers were easily amused, so they developed a clever way to switch the values of two variables without using a temporary intermediate variable. Here's the basic solution.
value1 = 1010101
value2 = 2020202
# Switch values by using xor.
value1 ^= value2
value2 ^= value1
value1 ^= value2
To make understanding the code easier, let's call the first value A and the second value B so initially value1 holds A and value2 holds B. The goal is to switch the values stored in the variables so value1 holds B and value2 holds A.
This code initializes two variables. It then uses the xor operator to execute value1 ^= value2 so value1 now contains A ^ B.
Next, the code performs value2 ^= value1 so value2 contains B ^ (A ^ B). The xor operator is commutative (we can change the order of operation) so this is the same as A ^ B ^ B. The two B values cancel each other leaving A, so value2 now holds A.
The code then executes value1 ^= value2 so value1 holds (A ^ B) ^ A. We rearrange this to A ^ A ^ B, the A values cancel, and we're left with B, so value1 holds B and we're done.
This is an interesting exercise in using the xor operator and its commutative property, but it's not a good programming practice because it's unnecessarily confusing. It's hardly worth the increased chance of confusion and mistakes to save one variable's worth of memory.
Besides, Python has this very elegant way to switch two values.
value1, value2 = value2, value1
And if you really need to track every single byte of memory, then Python is probably not the language for you.
In addition to using xor to switch two variables' values, you can use + and - like this.
value1 += value2
value2 = value1 - value2
value1 -= value2
The first statement makes value1 hold A + B.
The second statement makes value2 hold (A + B) - B = A + B - B = A.
Finally, the third statement makes value1 hold (A + B) - A = A - A + B = B.
I'll let you figure out how to make the switch by using * and /.
Here's the example program's code.
value1 = 1010101
value2 = 2020202
print(f'Initial: {value1=}, {value2=}')
# Switch values the proper way.
value1, value2 = value2, value1
print(f'Swap: {value1=}, {value2=}')
# Switch values by using xor.
value1 ^= value2
value2 ^= value1
value1 ^= value2
print(f'Xor: {value1=}, {value2=}')
# Switch values by using + and -.
value1 += value2
value2 = value1 - value2
value1 -= value2
print(f'+ and -: {value1=}, {value2=}')
# Switch values by using * and /.
...
print(f'* and /: {value1=}, {value2=}')
Download the example to see additional details, for example, if you can't figure out how to use * and / to switch the values.
|