import math
def euclidean(v1, v2):
total = 0
for i in range(len(v1)):
temp = v1[i] - v2[i]
total += temp ** 2
result = math.sqrt(total)
return result
def cosine_similarity(v1, v2):
sumxx, sumxy, sumyy = 0, 0, 0
for i in range(len(v1)):
x = v1[i]; y = v2[i]
sumxx += x*x
sumyy += y*y
sumxy += x*y
return sumxy/math.sqrt(sumxx*sumyy)
def distance(v1, v2, metric=euclidean):
dist = metric(v1, v2)
return dist
>>> euclidean([1,1], [2,2])
1.4142135623730951
>>> cosine_similarity([1,1], [2,2])
1.0
>>> distance([1,1], [2,2], euclidean)
1.4142135623730951
>>> distance([1,1], [2,2], cosine_similarity)
1.0