I have a tuple of '0'
and '1'
, and I want the xor of all its element. For example, if I have ('0', '1', '1', '0')
, I want to obtain ((0 xor 1) xor 1) xor 0
.
I have the following (working) snippet:
bit = ('0', '1', '0', '1', '0', '1', '0')
out = bit[0]
for i in range(1, len(bit)):
out = int(out) ^ int(bit[i])
print str(out)
How can I make it in a more pythonic way (using map
and a lambda function ?)
Approach: In order to find the XOR of all elements in the array, we simply iterate through the array and find the XOR using '^' operator.
Python program to perform XOR on two listsUsing the zip module to use simultaneous value each from the list. All elements are in Decimal and output is also in Decimal. ” ^ ” is using for 'exclusive or' in python.
In Python, we can perform the bitwise XOR operation using the "^" symbol. The XOR operation can be used for different purposes; XOR of two integers, XOR of two booleans, Swapping two numbers using XOR, etc. We can also use the xor() function using the operator module in Python.
XOR is defined as exclusive or for two integers say a and b. To find XOR, we will first find the binary representation of both a and b. Lets do this also by example. Suppose a = 7 and b = 10.
print reduce(lambda i, j: int(i) ^ int(j), bit)
reduce(...) reduce(function, sequence[, initial]) -> value
Apply a function of two arguments cumulatively to the items of a sequence, from left to right, so as to reduce the sequence to a single value. For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates ((((1+2)+3)+4)+5). If initial is present, it is placed before the items of the sequence in the calculation, and serves as a default when the sequence is empty.
As has been mentioned, reduce
works well. If you read about reduce
, you will come across the concept of a fold which is a higher order function (like map
).
In some languages you can fold left or right. Interestingly in your case, you would get the same result if you started from the left or the right as xor
is commutative and associative.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With