两个二进制字符串之间的汉明距离不起作用

2024-10-05 14:26:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我找到了一个有趣的算法来计算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'

我怎样才能让他们使用这个算法?


Tags: the字符串算法距离len站点defcount
3条回答

如果我们要坚持原来的算法,我们需要将字符串转换为整数才能使用按位运算符。

def hamming2(x_str, y_str):
    """Calculate the Hamming distance between two bit strings"""
    assert len(x_str) == len(y_str)
    x, y = int(x_str, 2), int(y_str, 2)  # '2' specifies we are reading a binary number
    count, z = 0, x ^ y
    while z:
        count += 1
        z &= z - 1  # magic!
    return count

我们可以这样称呼它:

print(hamming2('100010', '101000'))

虽然这种算法很酷,但必须转换成字符串可能会抵消它可能具有的任何速度优势。@dlask发布的答案要简洁得多。

实施它:

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

这就是我用来计算汉明距离的方法。
它计算等长字符串之间的差异。

def hamdist(str1, str2):
    diffs = 0
    for ch1, ch2 in zip(str1, str2):
        if ch1 != ch2:
            diffs += 1
    return diffs

相关问题 更多 >