class Vector: def init(self, lst): self.lst = lst

def dimension(self):
    return len(self.lst)

def magnitude(self):
    return sum(i**2 for i in self.lst)**0.5

def __add__(self, other):
    if self.dimension() != other.dimension():
        raise ValueError('The dimensions of the two vectors are not the same')
    return Vector([self.lst[i] + other.lst[i] for i in range(self.dimension())])

def dot(self, other):
    if self.dimension() != other.dimension():
        raise ValueError('The dimensions of the two vectors are not the same')
    return sum(self.lst[i] * other.lst[i] for i in range(self.dimension()))

def distance(self, other):
    if self.dimension() != other.dimension():
        raise ValueError('The dimensions of the two vectors are not the same')
    return sum((self.lst[i] - other.lst[i])**2 for i in range(self.dimension()))**0.
定义n维空间的向量类Vector 使用list类型成员存储向量。编写代码计算向量的长度维数、模及两个向量的和、内积、距离的方法。

原文地址: http://www.cveoy.top/t/topic/ck92 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录