Files
2026-04-21 11:27:40 +08:00

53 lines
1.4 KiB
Python
Raw Permalink 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.

# 题目1
s = "Hello"
# 1. 用 ord() 函数打印每个字符的 ASCII 码
print("1. 'Hello' 每个字符的 ASCII 码:")
for char in s:
ascii_code = ord(char)
print(f"字符 '{char}' 的 ASCII 码:{ascii_code}")
# 2. 用 chr() 函数验证字符65对应的是大写字母A
print("\n2. 验证 chr() 函数:")
char_from_code = chr(65)
print(f"ASCII 码 65 对应的字符是:'{char_from_code}'")
# 题目2
# 题目3
import math
print("===== 题目3 计算 =====")
A = [3, 4]
B = [1, 2]
add_result = [a + b for a, b in zip(A, B)]
print("A + B =", add_result)
# 2. 数乘 2*A
mul_result = [2 * x for x in A]
print("2 * A =", mul_result)
# 3. 向量 A 的模长
norm_A = math.sqrt(A[0]**2 + A[1]**2)
print("A 的模长 =", norm_A)
# 题目4
print("\n===== 题目4 计算 =====")
A4 = [1, 2, 3]
B4 = [4, 5, 6]
dot_product = sum(a * b for a, b in zip(A4, B4))
print("A · B =", dot_product)
norm_A4 = math.sqrt(sum(x**2 for x in A4))
norm_B4 = math.sqrt(sum(x**2 for x in B4))
cos_sim = dot_product / (norm_A4 * norm_B4)
print("A 的模长 =", round(norm_A4, 4))
print("B 的模长 =", round(norm_B4, 4))
print("余弦相似度 =", round(cos_sim, 4))
print("\n===== 特殊向量余弦相似度 =====")
A0 = [1, 0]
B0 = [0, 1]
dot0 = A0[0] * B0[0] + A0[1] * B0[1]
norm0_A = math.sqrt(A0[0]**2 + A0[1]**2)
norm0_B = math.sqrt(B0[0]**2 + B0[1]**2)
cos0 = dot0 / (norm0_A * norm0_B)
print("A=[1,0], B=[0,1] 余弦相似度 =", cos0)