我是python的新手,我遇到了这段代码,以在列表中找到单个元素
这是代码:
def single_number(arr):
ones, twos = 0, 0
for x in arr:
ones, twos = (ones ^ x) & ~twos, (ones & x) | (twos & ~x)
assert twos == 0
return ones
arr1 = [5, 3, 4, 3, 5, 5, 3]
print(single_number(arr1))
我似乎无法理解生产线在做什么
ones, twos = (ones ^ x) & ~twos, (ones & x) | (twos & ~x)
assert twos==0
除非您确实受内存空间限制,否则您不希望这样做,即使那样,您也可能不应该使用它。
这是某种位移/位操作“魔术”,即
Counter在O(n)中工作-这就是检查列表中所有元素的最佳方法-在此位上,它需要花费更多的固定时间(以设置Counter对象)和一些空间(以维护内部命令)-转移你发现的东西。
def getSingle(arr):
from collections import Counter
c = Counter(arr)
return c.most_common()[-1] # return the least common one -> (key,amounts) tuple
arr1 = [5, 3, 4, 3, 5, 5, 3]
counter = getSingle(arr1)
print (f"{counter[0]} occured {counter[1]} time(s)")
输出:
4 occured 1 time(s)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句