Shan-x
Shan-x

Reputation: 1186

xor of elements of a list/tuple

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

Upvotes: 17

Views: 30126

Answers (4)

Jackson Jegatheesan
Jackson Jegatheesan

Reputation: 668

Kidly take a look at this version is if you are looking for a solution without using reduce or lambda function

A = [1,1,2,3,4,4,5,5]
x = 0
for i in A:
    x ^= i

print(x)
output : 3

Upvotes: 1

beoliver
beoliver

Reputation: 5759

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.

Upvotes: 2

Eugene Yarmash
Eugene Yarmash

Reputation: 150041

In Python 3 you can use:

>>> from functools import reduce
>>> from operator import xor
>>> bits = ('0', '1', '0', '1', '0', '1', '0')
>>> reduce(xor, map(int, bits))
1

Or if you want a running XOR:

>>> from itertools import accumulate
>>> from operator import xor
>>> bits = ('0', '1', '0', '1', '0', '1', '0')
>>> list(accumulate(map(int, bits), xor))
[0, 1, 1, 0, 0, 1, 1]

Upvotes: 5

zephor
zephor

Reputation: 747

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.

Upvotes: 26

Related Questions