# 也是用于内容推荐 def pearson(p,q): 只计算两者共同有的 same = 0 for i in p: if i q: same += 1 n = same 分别求p,q的和 sumx = sum([p[i] range(n)]) sumy = sum([q[i] range(n)]) 分别求出p,q的平方和 sumxsq = sum([p[i] ** 2 range(n)]) sumysq = sum([q[i] ** 2 求出p,q的乘积和 sumxy = sum([p[i] * q[i] print sumxy 求出pearson相关系数 up = sumxy - sumx * sumy / n down = ((sumxsq - pow(sumxsq,2) / n) * (sumysq - pow(sumysq,2) / n)) ** .5 若down为零则不能计算,return 0 if down == 0: return 0 r = up / down r p = [0,1,1] q = [0,1)">] print (pearson(p,q))
# 得出的结果是1.0