-
Notifications
You must be signed in to change notification settings - Fork 0
/
vector.py
56 lines (38 loc) · 1.55 KB
/
vector.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
from __future__ import annotations
"""
An implementation of a pure integer vector. Contains only the binary operations
necessary to meet the arithmetic operation properties of a vector, i.e., vector
addition, scalar multiplication, negation.
Also has a method to rotate clockwise 90 degrees for convenience in producing
perpendicular vectors.
The dot product is also available.
Properties of interest are primarily arithmetic: commutativity, associativity,
distributivity, identity.
"""
class Vector2:
def __init__(self, _x: int, _y: int, /) -> None:
self._x = _x
self._y = _y
def __str__(self) -> str:
return f"({self._x},{self._y})"
def __repr__(self) -> str:
return f"Vector2({self.__str__()})"
def __add__(self, other: Vector2) -> Vector2:
return Vector2(self._x + other._x, self._y + other._y)
def __radd__(self, other: Vector2) -> Vector2:
return other + self
def __mul__(self, scalar: int) -> Vector2:
return Vector2(scalar * self._x, scalar * self._y)
def __rmul__(self, scalar: int) -> Vector2:
return Vector2(self._x * scalar, self._y * scalar)
def __neg__(self) -> Vector2:
return Vector2(-self._x, -self._y)
def __eq__(self, other: Vector2) -> bool:
return (self._x == other._x) and (self._y == other._y)
def rot90cw(self) -> Vector2:
return Vector2(self._y, -self._x)
@classmethod
def zero(cls) -> Vector2:
return cls(0, 0)
def dot(lhs: Vector2, rhs: Vector2) -> int:
return (lhs._x * rhs._x) + (lhs._y * rhs._y)