Python program to find distance measure - Hamming ,Euclidean , Manhattan, Minkowski

# Calculating distance between bit strings

# Hamming Distance
def hamming_distance(a, b):
return sum(abs(e1 - e2) for e1, e2 in zip(a, b)) / len(a)
r1 = [1, 0, 0, 0, 0, 0, 1]
r2 = [1, 0, 0, 0, 0, 1, 0]
dist = hamming_distance(r1, r2)
print(dist)

#Euclidean Distance
from math import sqrt
def euclidean_distance(a, b):
return sqrt(sum((e1-e2)**2 for e1, e2 in zip(a,b)))
r1 = [1, 0, 0, 0, 0, 0, 1]
r2 = [1, 0, 0, 0, 0, 1, 0]
dist = euclidean_distance(r1, r2)
print(dist)

#Manhattan Distance
from math import sqrt
def manhattan_distance(a, b):
return sum(abs(e1-e2) for e1, e2 in zip(a,b))
r1 = [1, 0, 0, 0, 0, 0, 1]
r2 = [1, 0, 0, 0, 0, 1, 0]
dist = manhattan_distance(r1, r2)
print(dist)

#Minkowski Distance
from math import sqrt
def minkowski_distance(a, b, p):
return sum(abs(e1-e2)**p for e1, e2 in zip(a,b))**(1/p)
r1 = [1, 0, 0, 0, 0, 0, 1]
r2 = [1, 0, 0, 0, 0, 1, 0]
dist = minkowski_distance(r1, r2, 1) #  p=1: Manhattan distance.
print(dist)
dist = minkowski_distance(r1, r2, 2) #  p=2: Euclidean distance.
print(dist)

No comments: