بتل کد Battle Codeدارد باز می‌شود…

جواب «Vector Operators» چالش 9 از جلسه‌ی 28

سؤال

کلاس Vector(x, y) با __add__، __sub__، __mul__ (ضرب در عدد)، __abs__ (طول)، __eq__ و __repr__ (Vector(<x>, <y>)) بنویسید. ورودی: خط اول x1 y1، خط دوم x2 y2، خط سوم عدد صحیح k (همه صحیح). پنج خط چاپ کنید: a + b، a - b، a * k، abs(a - b) با ۲ رقم اعشار، و a + b == b + a.

راهنما

__abs__ همان math.hypot(x, y) است. برای چاپ مستقیم شیء __repr__ کافی است.

یک جواب درست

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 __abs__(self):
        return math.hypot(self.x, self.y)

    def __eq__(self, other):
        return (self.x, self.y) == (other.x, other.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(f"{abs(a - b):.2f}")
print(a + b == b + a)

اول خودت امتحان کن؛ جواب‌های دیگر هم قبول است. برگرد و خودت حلش کن