Reputation: 41
class Vector:
def __init__(self, vector):
self.vector = vector
def __eq__(self, other):
return self.vector==other.vector
#above must not be changed. Below is my work.
#def __str__(self):
# return self.vector ---Not sure how to use __str__ on a list---
def __add__(self,other):
vector = Vector(self.vector+other.vector)
return vector
I know this is a wrong method but I have no clue how to work with a list. I just want to know how to work with a list in a class. Also, the following statement should work:
x=Vector([2,4,6]) #This is a list right? This is where I get stuck.
y=Vector([7,8,9])
print(x+y==Vector([9.12.15]))
I don't want the answer to all the operations just the add is enough. I just don't understand how to output lists in classes without the statement "a.vector" which clearly was not used the commands given above when creating objects for classes.
Also please specify if any clarification is required. Any help is appreciated! I am new to programming and just learnt classes in Python. Thanks a lot on advance
Upvotes: 0
Views: 64
Reputation: 59166
The result of adding two vectors of length 3 should be a vector with 3 elements, where each element is the sum of the corresponding elements in the original two vectors.
def __add__(self,other):
return Vector([a+b for a,b in zip(self.vector, other.vector)])
This uses zip
to iterate through both the starting vectors together, and constructs the new list using a list comprehension.
>>> x = Vector([2,4,6])
>>> y = Vector([7,8,9])
>>> x+y==Vector([9,12,15])
True
More:
If you want to support scalar multiplication, as indicated by your comments, then your other
operand is not another vector, but a number. So you need to multiply each element individually by that number.
def __mul__(self, other):
return Vector([a*other for a in self.vector])
__rmul__ = __mul__
This should allow you to perform both v*5
and 5*v
where v
is a Vector
object.
>>> x = Vector([2,4,6])
>>> x*5==Vector([10,20,30])
True
More
Here is an example of how you might write a dot-product between two vectors:
def dot(self, other):
return sum(a*b for (a,b) in zip(self.vector, other.vector))
>>> x = Vector([1,2,3])
>>> y = Vector([3,2,1])
>>> x.dot(y)
10
Upvotes: 1