两个二进制字符串之间的汉明距离不起作用 [英] Hamming distance between two binary strings not working

查看:290
本文介绍了两个二进制字符串之间的汉明距离不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I found an interesting algorithm to calculate hamming distance on this site:

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

关键是该算法仅适用于位字符串,我正在尝试比较两个二进制但字符串形式的字符串,例如

The point is that this algorithm only works on bit strings and I'm trying to compare two strings that are binary but they are in string format, like

'100010'
'101000'

如何使它们与该算法配合使用?

How can I make them work with this algorithm?

推荐答案

实施:

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

这篇关于两个二进制字符串之间的汉明距离不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆