上传文件至 /
This commit is contained in:
14
yzz.py
Normal file
14
yzz.py
Normal file
@@ -0,0 +1,14 @@
|
||||
# 方式1:直接用字符串表示 "Hello"
|
||||
str1 = "Hello"
|
||||
# 方式2:用单引号包裹表示 "Hello"
|
||||
str2 = 'Hello'
|
||||
|
||||
print("方式1(双引号):", str1)
|
||||
print("方式2(单引号):", str2)
|
||||
|
||||
print("\n--- Hello 每个字符的ASCII码 ---")
|
||||
for char in "Hello":
|
||||
print(f"字符 '{char}' 的ASCII码:{ord(char)}")
|
||||
|
||||
print("\n--- chr() 函数验证 ---")
|
||||
print(f"ASCII码 65 对应的字符:{chr(65)}")
|
||||
32
yzz1.py
Normal file
32
yzz1.py
Normal file
@@ -0,0 +1,32 @@
|
||||
# 定义向量 A 和 B
|
||||
A = [3, 4]
|
||||
B = [1, 2]
|
||||
|
||||
# ======================
|
||||
# 方法1:纯Python手动计算(适合理解原理)
|
||||
# ======================
|
||||
print("==== 纯Python计算结果 ====")
|
||||
# 1. 向量加法 A + B
|
||||
add_result = [A[0]+B[0], A[1]+B[1]]
|
||||
print("A + B =", add_result)
|
||||
|
||||
# 2. 数乘 2×A
|
||||
mul_result = [2*A[0], 2*A[1]]
|
||||
print("2 × A =", mul_result)
|
||||
|
||||
# 3. 向量A的长度(模):勾股定理 √(x²+y²)
|
||||
import math
|
||||
norm_A = math.sqrt(A[0]**2 + A[1]**2)
|
||||
print("A 的长度(模)= %.2f" % norm_A)
|
||||
|
||||
# ======================
|
||||
# 方法2:NumPy库(工业界标准写法)
|
||||
# ======================
|
||||
print("\n==== NumPy计算结果 ====")
|
||||
import numpy as np
|
||||
A_np = np.array([3, 4])
|
||||
B_np = np.array([1, 2])
|
||||
|
||||
print("A + B =", A_np + B_np) # 加法
|
||||
print("2 × A =", 2 * A_np) # 数乘
|
||||
print("A 的长度(模)= %.2f" % np.linalg.norm(A_np)) # 模长
|
||||
27
yzz2.py
Normal file
27
yzz2.py
Normal file
@@ -0,0 +1,27 @@
|
||||
import math
|
||||
|
||||
# 向量 A, B
|
||||
A = [1, 2, 3]
|
||||
B = [4, 5, 6]
|
||||
|
||||
# ========== 1. 计算点积 ==========
|
||||
dot = A[0]*B[0] + A[1]*B[1] + A[2]*B[2]
|
||||
print("A · B =", dot)
|
||||
|
||||
# ========== 2. 计算余弦相似度 ==========
|
||||
# 模长
|
||||
norm_A = math.sqrt(A[0]**2 + A[1]**2 + A[2]**2)
|
||||
norm_B = math.sqrt(B[0]**2 + B[1]**2 + B[2]**2)
|
||||
|
||||
# 余弦相似度
|
||||
cos_sim = dot / (norm_A * norm_B)
|
||||
print("余弦相似度 =", round(cos_sim, 4))
|
||||
|
||||
# ========== 3. A=[1,0], B=[0,1] 的余弦相似度 ==========
|
||||
A2 = [1, 0]
|
||||
B2 = [0, 1]
|
||||
dot2 = A2[0]*B2[0] + A2[1]*B2[1]
|
||||
norm_A2 = math.sqrt(A2[0]**2 + A2[1]**2)
|
||||
norm_B2 = math.sqrt(B2[0]**2 + B2[1]**2)
|
||||
cos_sim2 = dot2 / (norm_A2 * norm_B2)
|
||||
print("\nA=[1,0], B=[0,1] 余弦相似度 =", cos_sim2)
|
||||
Reference in New Issue
Block a user