Classes: Vector
Please Log In for full access to the web site.
Note that this link will take you to an external site (https://shimmer.mit.edu) to authenticate, and then you will be redirected back to this page.
For this exercise, define a class called Vector to represent n-dimensional vectors.
Your class's __init__ method should take as arguments self and a list
containing the numbers in the vector.
Your class must provide the following methods:
-
as_list(self), which returns a list containing the numbers in the vector. (It should not return a NumPy array or any other type.) -
__len__(self), which returns an integer containing the number of elements in the vector. -
magnitude(self), which should return the magnitude of the vector. -
__add__(self, other), which returns a new instance ofVectorrepresenting the sum of the original instance andother:- if
otheris an instance ofVectorwith appropriate size, your code should perform a vector addition. - otherwise, return
None(indicating an error)
- if
-
__sub__(self, other), which should behave analogously toadd, but should perform subtraction. Mathematically, this should be equivalent to self - other, where we subtract the vectorotherfrom the vectorself. -
__mul__(self, other), which returns a value representing the result of multiplying the original instance andotheraccording to the following rules:- if
otheris an instance ofVectorwith appropriate dimensions, your code should compute and return the dot product ofselfandother. - if
otheris an instance ofVectorwhose dimensions don't allow for computing the dot product, your code should returnNone. - if
otheris anintorfloat, return a new instance ofVectorwhose elements are the result of multiplying every entry of the original vector byother - otherwise, return
None(indicating an error)
- if
-
normalized(self), which should return a new instance ofVectorthat is a unit vector (vector of length 1) pointing in the same direction as the original vector. (Hint, consider using methods you have defined to multiply the vector by one over the magnitude).
You may wish to use Python's built-in isinstance function to check the type of other.
Notice that writing the double underscore methods enables you to use normal multiplication, division, addition, and subtraction with your Vectors (as we did in these tests)! Under the hood, Python is calling your methods to perform these operations!
Next Exercise: Shipping with APIs
6.s090