Approach #1 : We could broadcast them into binary bits & count number of different bits, like so -
def hamming_distance(a, b):
r = (1 << np.arange(8))[:,None]
return np.count_nonzero( (a & r) != (b & r) )
Sample run -
In [144]: a = [127,255]
...: b = [127,240]
...:
In [145]: hamming_distance(a, b)
Out[145]: 4
Approach #2 : Using bitwise-xor
operation, we can find out the number of different binary bits between a
and b
-
def hamming_distance_v2(a, b):
r = (1 << np.arange(8))[:,None]
return np.count_nonzero((np.bitwise_xor(a,b) & r) != 0)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…