Search code examples
pythonbinarybithamming-distance

Hamming distance between two binary strings not working


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?


Solution

  • Implement it:

    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))
    

    And test it:

    assert hamming2("1010", "1111") == 2
    assert hamming2("1111", "0000") == 4
    assert hamming2("1111", "1111") == 0