大厂笔试题
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

33 lines
1.1 KiB

2 weeks ago
  1. import math
  2. # 定义向量x和y
  3. x = (0, 1, 0, 1)
  4. y = (1, 0, 1, 0)
  5. # 计算余弦相似度
  6. def cosine(x, y):
  7. numerator = sum([x[i] * y[i] for i in range(len(x))])
  8. denominator = math.sqrt(sum([x[i] ** 2 for i in range(len(x))])) * math.sqrt(sum([y[i] ** 2 for i in range(len(y))]))
  9. return numerator / denominator
  10. # 计算相关系数
  11. def correlation(x, y):
  12. n = len(x)
  13. sum_x = sum(x)
  14. sum_y = sum(y)
  15. sum_xy = sum([x[i] * y[i] for i in range(n)])
  16. sum_x2 = sum([x[i] ** 2 for i in range(n)])
  17. sum_y2 = sum([y[i] ** 2 for i in range(n)])
  18. numerator = n * sum_xy - sum_x * sum_y
  19. denominator = math.sqrt((n * sum_x2 - sum_x ** 2) * (n * sum_y2 - sum_y ** 2))
  20. return numerator / denominator
  21. # 计算Jaccard系数
  22. def jaccard(x, y):
  23. intersection = sum([x[i] and y[i] for i in range(len(x))])
  24. union = sum([x[i] or y[i] for i in range(len(x))])
  25. return intersection / union
  26. # 输出结果
  27. print('余弦相似度:', cosine(x, y))
  28. print('相关系数:', correlation(x, y))
  29. print('Jaccard系数:', jaccard(x, y))