While reviewing the solution of a problem from the Python Data Structure and Algorithm course I am taking on Udemy, I got confused at the concept of "XOR".
As you can see below, we started off with 2 lists- arr1 and arr2, and then the solution basically tries to find the number in arr1 that is not in arr2 (which is 5 in this example). The "XOR" appears in the line "result^=num", and I have no idea how the "result" variable changes based on value of "num".
arr1 = [1,2,3,4,5,6,7]
arr2 = [3,7,2,1,4,6]
result = 0
for num in arr1+arr2:
print('result is ' + str(result))
print('num is ' + str(num))
result^=num
print('result is ' + str(result))
print()
print()
print('final result is ' + str(result))
Output:
result is 0
num is 1
result is 1
result is 1
num is 2
result is 3
result is 3
num is 3
result is 0
result is 0
num is 4
result is 4
result is 4
num is 5
result is 1
result is 1
num is 6
result is 7
result is 7
num is 7
result is 0
result is 0
num is 3
result is 3
result is 3
num is 7
result is 4
result is 4
num is 2
result is 6
result is 6
num is 1
result is 7
result is 7
num is 4
result is 3
result is 3
num is 6
result is 5
final result is 5
I know for example when input 1 equals input 2 then XOR will become "0". If input 1 is 0 and input 2 is 1 OR if input 1 is 1 and input 2 is 0 then XOR will return "1". But I don't understand is what if input 1 and input 2 are not the same and they are not 1 or 0. Let's say when input 1 is 10 and input 2 is 15 OR if input 1 is 15 and input 2 is 10 then XOR will return "5". But why is "5" the XOR output in this case?
Any idea to help me better understand the relationship between inputs and their XOR outputs will be greatly appreciated, hopefully in a not-so-technical manner!