Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python equivalent of sum() using xor()

Tags:

python

sum

xor

I like the Python sum function :

>>> z = [1] * 11
>>> zsum = sum(z)
>>> zsum == 11
True

I want the same functionality with using xor (^) not add (+). I want to use map. But I can not work out how to do this. Any hints?

I am not satisfied with this :

def xor(l):
    r = 0
    for v in l: r ^= v
    return v

I want a 1 liner using map. Hints?

like image 980
Cris Stringfellow Avatar asked Jan 28 '13 13:01

Cris Stringfellow


People also ask

How do you do XOR sum?

The XOR sum of a list is the bitwise XOR of all its elements. If the list only contains one element, then its XOR sum will be equal to this element. For example, the XOR sum of [1,2,3,4] is equal to 1 XOR 2 XOR 3 XOR 4 = 4 , and the XOR sum of [3] is equal to 3 .

Is XOR equal to addition?

It is called "parity" addition or "XOR" (The word XOR originated from exclusive-OR). We still call it addition because this operation has many properties in common with standard decimal (or binary) addition: it is commutative and associative, and "adding" zero to a number doesn't change the number.

When the sum and XOR are same?

Equal Sum and XOR in C++ In this problem, we are given an integer n. Our task is to create a program to find the count of integers from i = 0 to n, where sum is equal to XOR i.e. (n+i) = (n^i).


1 Answers

Note that starting Python 3.8, and the introduction of assignment expressions (PEP 572) (:= operator), we can use and update a variable within a list comprehension and thus reduce a list to the xor of its elements:

zxor = 0
[zxor := zxor ^ x for x in [1, 0, 1, 0, 1, 0]]
# zxor = 1
like image 142
Xavier Guihot Avatar answered Oct 01 '22 13:10

Xavier Guihot