Vector

The questions below are due on Sunday August 04, 2024; 10:00:00 PM.
 
You are not logged in.

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 of Vector representing the sum of the original instance and other:

    • if other is an instance of Vector with appropriate size, your code should perform a vector addition.
    • otherwise, return None (indicating an error)
  • __sub__(self, other), which should behave analogously to add, but should perform subtraction. Mathematically, this should be equivalent to self - other, where we subtract the vector other from the vector self.

  • __mul__(self, other), which returns a value representing the result of multiplying the original instance and other according to the following rules:

    • if other is an instance of Vector with appropriate dimensions, your code should compute and return the dot product of self and other.
    • if other is an instance of Vector whose dimensions don't allow for computing the dot product, your code should return None.
    • if other is an int or float, return a new instance of Vector whose elements are the result of multiplying every entry of the original vector by other
    • otherwise, return None (indicating an error)
  • normalized(self), which should return a new instance of Vector 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.

  No file selected

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

Back to exercises