#定义几种距离计算函数
#更高效的方式为把得分向量化之后使用scipy中定义的distance方法
from math import sqrt
def euclidean_dis(rating1, rating2): #欧式距离计算
“””计算2个打分序列间的欧式距离. 输入的rating1和rating2都是打分dict
格式为{‘小时代4’: 1.0, ‘疯狂动物城’: 5.0}”””
distance = 0
commonRatings = False
for key in rating1:
if key in rating2:
distance += (rating1[key] – rating2[key])^2
commonRatings = True
#两个打分序列之间有公共打分电影
if commonRatings:
return distance
#无公共打分电影
else:
return -1
def manhattan_dis(rating1, rating2): #曼哈顿距离计算
“””计算2个打分序列间的曼哈顿距离. 输入的rating1和rating2都是打分dict
格式为{‘小时代4’: 1.0, ‘疯狂动物城’: 5.0}”””
distance = 0
commonRatings = False
for key in rating1:
if key in rating2:
distance +=