Overload + for 2D Vectors

Medium ⏱ 12 min 64% acceptance ★★★★★ 4.5
Implement Vector(x, y) supporting v1 + v2 (component-wise, returning a new Vector) and v * k (scalar multiply via __mul__). Include a __repr__ like 'Vector(3, 4)' so results are readable. Do not mutate the operands.

Examples

Example 1
Input
repr(Vector(1, 2) + Vector(3, 4))
Output
'Vector(4, 6)'
Explanation

__add__ builds a fresh instance.

Constraints

  • Return new objects from both operators.
  • __repr__ format as shown.

Topics

OOPoperator overloading

Companies

GoogleNVIDIAIntel

Hints

Hint 1

def __add__(self, other): return Vector(...).

Hint 2

__mul__ takes the scalar as its second parameter.

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.