Python equivalent of sum() using xor()

一笑奈何 提交于 2019-11-30 03:28:13

问题


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?


回答1:


zxor = reduce(lambda a, b: a ^ b, z, 0)

import operator
zxor = reduce(operator.xor, z, 0)



回答2:


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


来源:https://stackoverflow.com/questions/14562991/python-equivalent-of-sum-using-xor

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!