Operator Overloading
Completed
Create Vector(x, y) supporting +, -, multiplication by a number (v * 3), == and abs(v) (length). Read two vectors and a number; print a + b, a - b, a * k, a == b and abs(a) (2 decimals). Vectors print as Vector(x, y).
Input
Three lines: ax ay, bx by, k.
Output
Five lines.
Example
Input
3 4 1 2 2
Output
Vector(4, 6) Vector(2, 2) Vector(6, 8) False 5.00
Editor
Python
Hints
a + b calls a.__add__(b).
Define __repr__ so print shows Vector(x, y).
Solution explanation
"Dunder" (double underscore) methods let your objects work with Python's operators and built-ins.
Show solution
import math
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)
def __sub__(self, other):
return Vector(self.x - other.x, self.y - other.y)
def __mul__(self, k):
return Vector(self.x * k, self.y * k)
def __eq__(self, other):
return (self.x, self.y) == (other.x, other.y)
def __abs__(self):
return math.hypot(self.x, self.y)
def __repr__(self):
return f"Vector({self.x}, {self.y})"
a = Vector(*map(int, input().split()))
b = Vector(*map(int, input().split()))
k = int(input())
print(a + b)
print(a - b)
print(a * k)
print(a == b)
print(f"{abs(a):.2f}")