我有一个数字列表:
a = [1,2,3,4,5,19,22,25,17,6,73,72,71,77,899,887,44,124, ...]
#this is an abbreviated version of the list
我需要使用 XOR(“^”)运算符确定列表中是否有重复项。
谁能给我一些提示?我是新手,以前从未遇到过这个问题或使用过 XOR 运算符。
我已经尝试了几种方法(相当于在黑暗中盲目刺伤)。最后一个是这样的:
MyDuplicatesList = [1,5,12,156,166,2656,6,4,5,9] #changed the list to make it easer
for x in MyDuplicatesList:
if x^x:
print("True")
我意识到我问这样一个开放式问题可能违反了协议(protocol),但我完全被难住了。
请您参考如下方法:
为什么要异或?
# true if there are duplicates
print len(set(a)) != len(a)
好的,这是 pythonic。它找到所有重复项并列出它们。
a = [1,2,3,4,5,19,22,25,17,6,73,72,71,77,899,887,44,124,1]
b = [a[i] for i in range(len(a)) for j in range(i+1,len(a)) if i ^ j > 0 if a[i] ^ a[j] < 1]
print b
Dalen 想法的简化版:
a = [1,2,3,4,5,19,22,25,17,6,73,72,71,77,899,887,44,124,1]
def simplifyDalen(source):
dup = 0
for x in source:
for y in source:
dup += x ^ y == 0
return dup ^ len(source) > 0
result = simplifyDalen(a)
if result:
print "There are duplicates!"
else:
print "There are no duplicates!"
到目前为止我的位索引想法是最快的(因为它是一次通过算法,我猜,不是多对多)
