Oct-25-2020, 06:30 AM
Question:
For a given list of numbers, only one digit is repeated odd number of times. Pass the list through function and return the number which is repeated odd number of times.
I have a solution for it. But, I found another solution by other user which I did not understand. Here is the code
More explanation:
I have tried printing the binary values of result and x before and after statement result ^= x to understand what is happening but, could not.
Any other resources that you can point me to get better understanding?
Om
For a given list of numbers, only one digit is repeated odd number of times. Pass the list through function and return the number which is repeated odd number of times.
I have a solution for it. But, I found another solution by other user which I did not understand. Here is the code
def find_it(seq): result = 0 for x in seq: result ^= x return result find_it([1,2,3,1,2,3,1])XOR seems to be implemented but, how is the only odd number being detected.
More explanation:
I have tried printing the binary values of result and x before and after statement result ^= x to understand what is happening but, could not.
Any other resources that you can point me to get better understanding?
For value 1 , Before ^x Operation. bin(result) = 0b0 , bin(x) = 0b1 For value 1 , After ^x Operation. bin(result) = 0b1 , bin(x) = 0b1 Result = 1 For value 2 , Before ^x Operation. bin(result) = 0b1 , bin(x) = 0b10 For value 2 , After ^x Operation. bin(result) = 0b11 , bin(x) = 0b10 Result = 3 For value 3 , Before ^x Operation. bin(result) = 0b11 , bin(x) = 0b11 For value 3 , After ^x Operation. bin(result) = 0b0 , bin(x) = 0b11 Result = 0 For value 1 , Before ^x Operation. bin(result) = 0b0 , bin(x) = 0b1 For value 1 , After ^x Operation. bin(result) = 0b1 , bin(x) = 0b1 Result = 1 For value 2 , Before ^x Operation. bin(result) = 0b1 , bin(x) = 0b10 For value 2 , After ^x Operation. bin(result) = 0b11 , bin(x) = 0b10 Result = 3 For value 3 , Before ^x Operation. bin(result) = 0b11 , bin(x) = 0b11 For value 3 , After ^x Operation. bin(result) = 0b0 , bin(x) = 0b11 Result = 0 For value 1 , Before ^x Operation. bin(result) = 0b0 , bin(x) = 0b1 For value 1 , After ^x Operation. bin(result) = 0b1 , bin(x) = 0b1 Result = 1 For value 4 , Before ^x Operation. bin(result) = 0b1 , bin(x) = 0b100 For value 4 , After ^x Operation. bin(result) = 0b101 , bin(x) = 0b100 Result = 5 For value 4 , Before ^x Operation. bin(result) = 0b101 , bin(x) = 0b100 For value 4 , After ^x Operation. bin(result) = 0b1 , bin(x) = 0b100 Result = 1 1 Process finished with exit code 0Thanks,
Om