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:

  1. xor of number 0

  2. xor of number 0 number itself

  3. 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

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -