使用【python】写【文本相似度分析】的代码创建一个vector类,完成vector向量的所有基本操作
时间: 2024-10-10 16:06:24 浏览: 28
```python
class Vector:
def __init__(self, elements):
self.elements = elements
def __add__(self, other):
if len(self.elements) != len(other.elements):
raise ValueError("向量长度不匹配")
return Vector([a + b for a, b in zip(self.elements, other.elements)])
def __sub__(self, other):
if len(self.elements) != len(other.elements):
raise ValueError("向量长度不匹配")
return Vector([a - b for a, b in zip(self.elements, other.elements)])
def dot(self, other):
if len(self.elements) != len(other.elements):
raise ValueError("向量长度不匹配")
return sum(a * b for a, b in zip(self.elements, other.elements))
def magnitude(self):
return sum(x ** 2 for x in self.elements) ** 0.5
def __str__(self):
return str(self.elements)
# 示例
v1 = Vector([1, 2, 3])
v2 = Vector([4, 5, 6])
print("v1 + v2 =", v1 + v2)
print("v1 - v2 =", v1 - v2)
print("v1 · v2 =", v1.dot(v2))
print("|v1| =", v1.magnitude())
print("|v2| =", v2.magnitude())
```
阅读全文