我找到了一个有趣的算法来计算this站点上的hamming距离:
def hamming2(x,y):
"""Calculate the Hamming distance between two bit strings"""
assert len(x) == len(y)
count,z = 0,x^y
while z:
count += 1
z &= z-1 # magic!
return count
关键是这个算法只对位字符串起作用,我试图比较两个二进制字符串,但它们是字符串格式的,比如
'100010'
'101000'
我怎样才能让他们使用这个算法?
如果我们要坚持原来的算法,我们需要将字符串转换为整数才能使用按位运算符。
我们可以这样称呼它:
虽然这种算法很酷,但必须转换成字符串可能会抵消它可能具有的任何速度优势。@dlask发布的答案要简洁得多。
实施它:
测试它:
这就是我用来计算汉明距离的方法。
它计算等长字符串之间的差异。
相关问题 更多 >
编程相关推荐