我在this网站上发现了一种有趣的算法来计算汉明距离:

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'

如何使他们使用此算法?

最佳答案

实现它:

def hamming2(s1, s2):
    """Calculate the Hamming distance between two bit strings"""
    assert len(s1) == len(s2)
    return sum(c1 != c2 for c1, c2 in zip(s1, s2))

并测试一下:
assert hamming2("1010", "1111") == 2
assert hamming2("1111", "0000") == 4
assert hamming2("1111", "1111") == 0

10-08 11:07