Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import math
- class Vector2D:
- def __init__(self, x: float = 0, y: float = 0):
- self.x = x
- self.y = y
- def __add__(self, other):
- return Vector2D(self.x + other.x, self.y + other.y)
- def __sub__(self, other):
- return Vector2D(self.x - other.x, self.y - other.y)
- def __mul__(self, other):
- if isinstance(other, (int, float)):
- num = other
- return Vector2D(self.x * num, self.y * num)
- elif isinstance(other, Vector2D): # kinda scalar_product()
- return Vector2D(self.x * other.x, self.y * other.y)
- raise ValueError
- def __str__(self) -> str:
- return f"Vector2D({self.x}, {self.y})"
- def __len__(self) -> int:
- return int(math.sqrt(self.x ** 2 + self.y ** 2))
- def __eq__(self, other) -> bool:
- return self.x == other.x and self.y == other.y
- def add(self, vector) -> None:
- self.x += vector.x
- self.y += vector.y
- def sub(self, vector) -> None:
- self.x -= vector.x
- self.y -= vector.y
- def mul(self, num) -> None:
- self.x *= num
- self.y *= num
- def cos(self, other) -> float:
- return float(
- (self.x * other.x + self.y * other.y) / len(self) * len(other)
- )
- def main():
- vector1 = Vector2D()
- vector2 = Vector2D(1, 3)
- vector3 = Vector2D(6, 66)
- print(vector1 + vector2)
- vector1.add(vector3)
- print(vector1)
- print(vector1 - vector2)
- vector1.sub(vector3)
- print(vector1)
- num = 5.7289314718
- print(vector2 * num)
- vector2.mul(num)
- print(vector2)
- print(len(vector2))
- print(vector2 * vector3)
- print(vector2.cos(vector3))
- print(vector2 == vector3)
- if __name__ == "__main__":
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement