Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Class for Vector
#1
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
Reply
#2
Please, don't post images of code. Copy/paste in python tags.
See BBcode help for more info.
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
(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
Reply
#4
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)
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#5
Oh, thanks. I didnt notice!
As you said - we need to use this "unpythonic" method, but thank you for info.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  vector field plots Larssauerkraut 0 1,501 Oct-15-2019, 11:15 AM
Last Post: Larssauerkraut
  Divide a vector Langosmon 1 2,665 May-13-2018, 09:09 AM
Last Post: ThiefOfTime
  Classification by support vector method qwerty 1 2,921 Apr-16-2017, 07:16 PM
Last Post: sparkz_alot
  vector sum of tuples roadrage 7 7,598 Nov-28-2016, 09:54 PM
Last Post: nilamo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020