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

50 lines
1.2 KiB
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.

s = "Hello"
for c in s:
print(c, ord(c))
print(chr(65))
# ========== 题目3 ==========
A = [3, 4]
B = [1, 2]
# 1. 向量加法
def vector_add(a, b):
return [x + y for x, y in zip(a, b)]
# 2. 数乘向量
def scalar_multiply(scalar, vec):
return [scalar * x for x in vec]
# 3. 计算向量的模
def vector_norm(vec):
return sum(x**2 for x in vec) ** 0.5
print("题目3")
print(f"1. A + B = {vector_add(A, B)}")
print(f"2. 2 × A = {scalar_multiply(2, A)}")
print(f"3. A的模 = {vector_norm(A)}")
print("-" * 30)
# ========== 题目4 ==========
A1 = [1, 2, 3]
B1 = [4, 5, 6]
A2 = [1, 0]
B2 = [0, 1]
# 1. 点积计算
def dot_product(a, b):
return sum(x * y for x, y in zip(a, b))
# 2. 余弦相似度计算
def cosine_similarity(a, b):
dot = dot_product(a, b)
norm_a = vector_norm(a)
norm_b = vector_norm(b)
return dot / (norm_a * norm_b) if norm_a != 0 and norm_b != 0 else 0
print("题目4")
print(f"1. A·B = {dot_product(A1, B1)}")
print(f"2. A1与B1的余弦相似度 = {cosine_similarity(A1, B1):.4f}")
print(f"3. A2与B2的余弦相似度 = {cosine_similarity(A2, B2)}")
print(" 原因两个向量正交点积为0方向完全垂直所以相似度为0")