From 9acc42005dc54a4b2fba7f1a52e6be26e61a5712 Mon Sep 17 00:00:00 2001 From: 2509165013 <2509165013@student.edu.cn> Date: Tue, 21 Apr 2026 11:25:11 +0800 Subject: [PATCH] =?UTF-8?q?=E5=AE=8C=E6=88=90=E4=BD=9C=E4=B8=9A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- 13zsk.py.py | 50 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 13zsk.py.py diff --git a/13zsk.py.py b/13zsk.py.py new file mode 100644 index 0000000..aa820fe --- /dev/null +++ b/13zsk.py.py @@ -0,0 +1,50 @@ +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") \ No newline at end of file