Exercise: Vectors

Time to put the special methods together.

Exercise: finish the 2D Vector class.

  • repr(Vector(1, 2)) is "Vector(1, 2)".
  • v + w adds the parts and returns a new Vector.
  • v * 3 and 3 * v scale both parts. Multiplying by anything that isn't an int or float should give a TypeError.
  • v == w is True when both parts match. Comparing with a non-Vector, like a tuple, is False.
  • abs(v) is the length. math.hypot(x, y) computes it.

Return NotImplemented for types you don't handle, and let Python raise the TypeError for you.

Extra, not tested: why can't you put a Vector in a set now? What would you change to allow it safely?

Press Check to run the tests.