Distance Formula

Quick notes

from scipy.spatial import distance

#Euclidean Distance (hyp)
distance.euclidean([1,2], [4,0])

#Manhattan Distance
distance.cityblock([1,2], [4,0])

#Hamming Distance, returns (normal ANSWER)/total
# below ans == 2/3 == 0.6666
distance.hamming([5, 4, 9], [1, 7, 9])

How it works...

Note: here we will represent points as lists

point = [1,2]
# x = 1, y = 2

Note: both points must have the same dimensions for any to work

Euclidean Distance

This finds the hypotenuse between two points

def euclidean_distance(pt1, pt2):
  ''' returns the shortest distence between two points '''
  distance = 0

  for i in range(len(pt1)):
    distance += (pt1[i] - pt2[i]) ** 2

  return distance ** 0.5

Manhattan Distance

This finds the sum of each side between two points

Note: | x | just makes the number positive, (known as absolute value)

def manhattan_distance(pt1, pt2):
	''' return to the Manhattan distance between two points '''
  distance = 0

  for i in range(len(pt1)):
    distance += abs(pt1[i] - pt2[i])

  return distance

Hamming Distance

Counts how many dimensions are not equal

def hamming_distance(pt1, pt2):
	''' how many dimensions are not equal '''
  distance = 0

  for i in range(len(pt1)):
    if pt1[i] != pt2[i]:
      distance += 1

  return distance