Editor

A 2D Vector Class

#295 · Classes · Intermediate · 70 XP · about 15 min

Python's operators call special methods: a + b runs a.__add__(b) and abs(v) runs v.__abs__(). Defining them makes your own class feel built in.

Build a Vector class for 2D vectors:

  • Vector(x, y) stores the two numbers as the attributes x and y.
  • v + w and v - w return a new Vector with the coordinates added or subtracted.
  • v * k and k * v return a new Vector with both coordinates multiplied by the number k. Multiplying by anything that is not an int or a float raises TypeError (return NotImplemented from the method and Python raises it for you).
  • v == w is True when both coordinates are equal. Comparing a Vector with something that is not a Vector gives False.
  • abs(v) returns the length of the vector, the square root of x * x + y * y, as a float.
  • repr(v) returns Vector(x, y) with each number written the way Python writes it, for example Vector(3, -4) or Vector(0.5, 1.0).

Examples

v = Vector(3, 4)
w = Vector(1, -2)
v + w               # Vector(4, 2)
v - w               # Vector(2, 6)
v * 2               # Vector(6, 8)
2 * v               # Vector(6, 8)
abs(v)              # 5.0
v == Vector(3, 4)   # True

Constraints

  • Coordinates are ints or floats

Note

2 * v is not the same call as v * 2. The number on the left does not know about vectors, so Python then asks the vector on the right, through __rmul__.

Fastest solvers

Leaderboard

First solves only, ranked by stars and then time.