完成作业X
This commit is contained in:
6
test.py
Normal file
6
test.py
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
#1
|
||||||
|
s = "Hello"
|
||||||
|
for char in s:
|
||||||
|
print(f"{char} 的ASCII码是{ord(char)}")
|
||||||
|
#2
|
||||||
|
print(chr(65))
|
||||||
11
test2.py
Normal file
11
test2.py
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
A = [3, 4]
|
||||||
|
B = [1, 2]
|
||||||
|
A_plus_B = [A[i] + B[i] for i in range(len(A))]
|
||||||
|
print("1. A + B =", A_plus_B)
|
||||||
|
two_mul_A = [2 * x for x in A]
|
||||||
|
print("2. 2 * A =", two_mul_A)
|
||||||
|
import math
|
||||||
|
def vector_norm(v):
|
||||||
|
return math.sqrt(sum(x ** 2 for x in v))
|
||||||
|
A_norm = vector_norm(A)
|
||||||
|
print("3. A 的模 =", A_norm)
|
||||||
23
test3.py
Normal file
23
test3.py
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
import math
|
||||||
|
A = [1, 2, 3]
|
||||||
|
B = [4, 5, 6]
|
||||||
|
def dot_product(v1, v2):
|
||||||
|
return sum(x * y for x, y in zip(v1, v2))
|
||||||
|
A_dot_B = dot_product(A, B)
|
||||||
|
print("1. A · B =", A_dot_B)
|
||||||
|
def vector_norm(v):
|
||||||
|
return math.sqrt(sum(x ** 2 for x in v))
|
||||||
|
def cosine_similarity(v1, v2):
|
||||||
|
dot = dot_product(v1, v2)
|
||||||
|
norm1 = vector_norm(v1)
|
||||||
|
norm2 = vector_norm(v2)
|
||||||
|
if norm1 == 0 or norm2 == 0:
|
||||||
|
return 0.0
|
||||||
|
return dot / (norm1 * norm2)
|
||||||
|
cos_sim = cosine_similarity(A, B)
|
||||||
|
print("2. 余弦相似度 =", round(cos_sim, 4))
|
||||||
|
A2 = [1, 0]
|
||||||
|
B2 = [0, 1]
|
||||||
|
cos_sim2 = cosine_similarity(A2, B2)
|
||||||
|
print("3. A=[1,0], B=[0,1] 的余弦相似度 =", cos_sim2)
|
||||||
|
print(" 原因:点积为 0,说明两向量正交,夹角为 90°,所以余弦相似度为 0。")
|
||||||
Reference in New Issue
Block a user