Python Forum

Full Version: Class for Vector
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello! Angel
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? Blush
Please, don't post images of code. Copy/paste in python tags.
See BBcode help for more info.
(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
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)
Oh, thanks. I didnt notice!
As you said - we need to use this "unpythonic" method, but thank you for info.