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