Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

xor of elements of a list/tuple

Tags:

python

xor

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 ?)

like image 930
Shan-x Avatar asked Nov 28 '15 10:11

Shan-x


People also ask

How do you find the XOR of all elements in a list?

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.

Can you XOR lists in Python?

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.

How is XOR calculated 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.

What is XOR of two elements?

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.


2 Answers

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.

like image 69
zephor Avatar answered Oct 21 '22 09:10

zephor


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.

like image 42
beoliver Avatar answered Oct 21 '22 10:10

beoliver