Files
task-3-2-1-Text-Processing-…/test 2.py
2026-04-21 11:25:48 +08:00

38 lines
851 B
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import math
# 题目3
A = [3, 4]
B = [1, 2]
A_plus_B = [A[0]+B[0], A[1]+B[1]]
two_A = [2*A[0], 2*A[1]]
norm_A = math.sqrt(A[0]**2 + A[1]**2)
print("题目3结果")
print(f"A+B = {A_plus_B}")
print(f"2*A = {two_A}")
print(f"A的模 = {norm_A}")
# 题目4
A = [1, 2, 3]
B = [4, 5, 6]
dot_product = sum(a*b for a,b in zip(A,B))
norm_A = math.sqrt(sum(a**2 for a in A))
norm_B = math.sqrt(sum(b**2 for b in B))
cos_sim = dot_product / (norm_A * norm_B)
print("\n题目4-1、2结果")
print(f"点积 = {dot_product}")
print(f"余弦相似度 = {cos_sim:.4f}")
# 题目4-3
A2 = [1, 0]
B2 = [0, 1]
dot_product2 = sum(a*b for a,b in zip(A2,B2))
norm_A2 = math.sqrt(sum(a**2 for a in A2))
norm_B2 = math.sqrt(sum(b**2 for b in B2))
cos_sim2 = dot_product2 / (norm_A2 * norm_B2)
print("\n题目4-3结果")
print(f"余弦相似度 = {cos_sim2}")