Advertisement
lllumineux

Untitled

Dec 1st, 2020
745
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.80 KB | None | 0 0
  1. import math
  2.  
  3.  
  4. class Vector2D:
  5.     def __init__(self, x: float = 0, y: float = 0):
  6.         self.x = x
  7.         self.y = y
  8.  
  9.     def __add__(self, other):
  10.         return Vector2D(self.x + other.x, self.y + other.y)
  11.  
  12.     def __sub__(self, other):
  13.         return Vector2D(self.x - other.x, self.y - other.y)
  14.  
  15.     def __mul__(self, other):
  16.         if isinstance(other, (int, float)):
  17.             num = other
  18.             return Vector2D(self.x * num, self.y * num)
  19.         elif isinstance(other, Vector2D):  # kinda scalar_product()
  20.             return Vector2D(self.x * other.x, self.y * other.y)
  21.         raise ValueError
  22.  
  23.     def __str__(self) -> str:
  24.         return f"Vector2D({self.x}, {self.y})"
  25.  
  26.     def __len__(self) -> int:
  27.         return int(math.sqrt(self.x ** 2 + self.y ** 2))
  28.  
  29.     def __eq__(self, other) -> bool:
  30.         return self.x == other.x and self.y == other.y
  31.  
  32.     def add(self, vector) -> None:
  33.         self.x += vector.x
  34.         self.y += vector.y
  35.  
  36.     def sub(self, vector) -> None:
  37.         self.x -= vector.x
  38.         self.y -= vector.y
  39.  
  40.     def mul(self, num) -> None:
  41.         self.x *= num
  42.         self.y *= num
  43.  
  44.     def cos(self, other) -> float:
  45.         return float(
  46.             (self.x * other.x + self.y * other.y) / len(self) * len(other)
  47.         )
  48.  
  49.  
  50. def main():
  51.     vector1 = Vector2D()
  52.     vector2 = Vector2D(1, 3)
  53.     vector3 = Vector2D(6, 66)
  54.  
  55.     print(vector1 + vector2)
  56.     vector1.add(vector3)
  57.     print(vector1)
  58.  
  59.     print(vector1 - vector2)
  60.     vector1.sub(vector3)
  61.     print(vector1)
  62.  
  63.     num = 5.7289314718
  64.     print(vector2 * num)
  65.     vector2.mul(num)
  66.     print(vector2)
  67.  
  68.     print(len(vector2))
  69.  
  70.     print(vector2 * vector3)
  71.  
  72.     print(vector2.cos(vector3))
  73.  
  74.     print(vector2 == vector3)
  75.  
  76.  
  77. if __name__ == "__main__":
  78.     main()
  79.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement