Calculate Hamming, Manhattan and Minkowski Distance

# calculate hamming distance
from math import sqrt


def hamming_distance(x, y):
    return sum(abs(a1 - a2) for a1, a2 in zip(x, y)) / len(x)


# define data
rowA = [0, 1, 0, 1, 0, 1]
rowB = [0, 1, 0, 0, 1, 0]
# calculate distance
result = hamming_distance(rowA, rowB)
print(result)


# calculate manhattan distance
def manhattan_distance(x, y):
    return sum(abs(a1-a2) for a1, a2 in zip(x, y))


# define data
rowA = [10, 30, 45, 10, 5]
rowB = [12, 24, 18, 8, 7]
# calculate distance
result = manhattan_distance(rowA, rowB)
print(result)


# calculate minkowski distance
def minkowski_distance(x, y, z):
    return sum(abs(a1-a2)**z for a1, a2 in zip(x, y))**(1/z)


# define data
rowA = [20, 40, 25, 30, 5]
rowB = [12, 10, 18, 10, 7]
# calculate distance (z=1)
result = minkowski_distance(rowA, rowB, 1)
print(result)
# calculate distance (z=2)
result = minkowski_distance(rowA, rowB, 2)
print(result)

Leave a Reply

Your email address will not be published. Required fields are marked *