python - XOR to find the missing element between two lists -
i try solve problem
"consider array of non-negative integers. second array formed shuffling elements of first array , deleting random element. given these 2 arrays, find element missing in second array."
and 1 of solution below code using xor
def find(arr1, arr2): result=0 # perform xor between numbers in arrays num in arr1+arr2: result^=num print result return result arr1 = [1,2,3,4,5,6,7] arr2 = [3,7,2,1,4,6]
the result of function 5.
i know basic principle of xor. can't understand how above code can find result.
some important concepts:
xor of number 0
xor of number 0 number itself
the order of xor operation inconsequential
with this, consider:
1 ^ 2 ^ 3 ^ 4 ^ 5 ^ 6 ^ 7 ^ 3 ^ 7 ^ 2 ^ 1 ^ 4 ^ 6 → (1 ^ 1) ^ (2 ^ 2) ^ (3 ^ 3) ^ (4 ^ 4) ^ (5) ^ (6 ^ 6) ^ (7 ^ 7) → 0 ^ 0 ^ 0 ^ 0 ^ 5 ^ 0 ^ 0 → 5
and so, odd 1 out remains.
Comments
Post a Comment