Class for Vector - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: Homework (https://python-forum.io/forum-9.html) +--- Thread: Class for Vector (/thread-21592.html) |
Class for Vector - no_named_nobody - Oct-06-2019 Hello! I am new in programming in python. I got a homework to create class MyVector, - constructor will accept (to self) one parameter (it will be one-dimensional array) - method get_vector(self) return one-dimensional array containing the vector elements - with special method __mul__(self,other) implement the dot product of two objects MyVector (the output is a scalar, so one number) btw I cant import other modules. I have this: [Image: ZvD49DyKCd.jpg] In my mind, get_vector(self) is right. But __mul__(self,other) is not working properly. Do you know how to make things right? RE: Class for Vector - buran - Oct-06-2019 Please, don't post images of code. Copy/paste in python tags. See BBcode help for more info. RE: Class for Vector - no_named_nobody - Oct-06-2019 (Oct-06-2019, 02:44 PM)buran Wrote: Please, don't post images of code. Copy/paste in python tags. See BBcode help for more info.Sorry, there is: class MyVector: def __init__(self, a): self.a = a def get_vector(self): return(self.a) def __mul__(self, other): dot_product = 0 for x in range(len(self.a)): dot_product += self.a[x]*other.a[x] return dot_product RE: Class for Vector - buran - Oct-06-2019 You need to dedent line 12 - i.e. you want to return dot_product only after the for loop ended. I understand that this is homework and you need to do what you are asked to do. However, for your information, using get function like this get_vector is not pythonic. i.e. you can just access the a property (of cource you want more meaningful name) RE: Class for Vector - no_named_nobody - Oct-06-2019 Oh, thanks. I didnt notice! As you said - we need to use this "unpythonic" method, but thank you for info. |