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 ofVector
representing the sum of the original instance andother
:- if
other
is an instance ofVector
with 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 vectorother
from the vectorself
. -
__mul__(self, other)
, which returns a value representing the result of multiplying the original instance andother
according to the following rules:- if
other
is an instance ofVector
with appropriate dimensions, your code should compute and return the dot product ofself
andother
. - if
other
is an instance ofVector
whose dimensions don't allow for computing the dot product, your code should returnNone
. - if
other
is anint
orfloat
, return a new instance ofVector
whose 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 ofVector
that 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 Vector
s (as we did in these tests)! Under the hood, Python is calling your methods to perform these operations!
Next Exercise: Shipping with APIs