类向量

编程入门 行业动态 更新时间:2024-10-23 11:22:50
向量 - 非特定维度的两个向量的乘法(Class vectors - multiplication of two vectors of non-specific dimension) class MyVector: def __init__(self, vector): # classic init self.vector = vector def get_vector(self): return self.vector def __mul__(self, other): for i in range(0, len(self.vector)): #cycle # if I did scalar_product += (self.vector[i] * other.vector[i]) here, # it didn't work scalar_product = (self.vector[i] * other.vector[i]) return (scalar_product) if __name__ == "__main__": #just testing program vec1 = MyVector([1, 2, 3, 4]) vec2 = MyVector([4, 5, 6, 7]) print(vec1.get_vector()) print(vec2.get_vector()) scalar_product = vec1*vec2 print(scalar_product) # shows only 4*7 but not others

我该怎么做才能使这个程序工作? 现在它只是将最后的数字相乘,例如4 * 7,而不是其他数字。

class MyVector: def __init__(self, vector): # classic init self.vector = vector def get_vector(self): return self.vector def __mul__(self, other): for i in range(0, len(self.vector)): #cycle # if I did scalar_product += (self.vector[i] * other.vector[i]) here, # it didn't work scalar_product = (self.vector[i] * other.vector[i]) return (scalar_product) if __name__ == "__main__": #just testing program vec1 = MyVector([1, 2, 3, 4]) vec2 = MyVector([4, 5, 6, 7]) print(vec1.get_vector()) print(vec2.get_vector()) scalar_product = vec1*vec2 print(scalar_product) # shows only 4*7 but not others

What do I have to do to make this program work? Now it just multiplies the last digits, for example 4 * 7, but not the other ones.

最满意答案

您需要首先定义标量产品:

def __mul__(self, other): scalar_product = 0 # or 0.0 for i in range(0, len(self.vector)): scalar_product += self.vector[i] * other.vector[i] return scalar_product

您还应该返回MyVector类型的对象

You need to define your scalar product first:

def __mul__(self, other): scalar_product = 0 # or 0.0 for i in range(0, len(self.vector)): scalar_product += self.vector[i] * other.vector[i] return scalar_product

You should also return an object of type MyVector

更多推荐

本文发布于:2023-08-05 17:11:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1437455.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:向量

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!