Core Point Class Implementation
class Point:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def __repr__(self):
return f'Point({self.x}, {self.y})'
Sequence Protocol Implementation
def __getitem__(self, index):
if index in {0, -2}:
return self.x
elif index in {1, -1}:
return self.y
raise IndexError("Invalid index")
def __setitem__(self, index, value):
if index in {0, -2}:
self.x = value
elif index in {1, -1}:
self.y = value
else:
raise IndexError("Invalid index")
def __len__(self):
return 2
Unary Operators
def __neg__(self):
return Point(-self.x, -self.y)
def __pos__(self):
return (
Point(self.x, self.y + 1),
Point(self.x, self.y - 1),
Point(self.x - 1, self.y),
Point(self.x + 1, self.y)
)
def __abs__(self):
return Point(abs(self.x), abs(self.y))
def __invert__(self):
return Point(self.y, self.x)
Callabel Objects and Boolean
def __call__(self, dx=0, dy=0):
return Point(self.x + dx, self.y + dy)
def __bool__(self):
return self.x >= 0 and self.y >= 0
Comparison Operators
def __eq__(self, other):
return self.x == other.x and self.y == other.y
def __ne__(self, other):
return not self == other
def __lt__(self, other):
return self.x == other.x and self.y != other.y
def __gt__(self, other):
return self.y == other.y and self.x != other.x
Bitwise Opreators
def __and__(self, other):
return self.x != other.x and self.y != other.y
def __or__(self, other):
return self.x == other.x or self.y == other.y
def __xor__(self, other):
return (self.x == other.x) != (self.y == other.y)
def __lshift__(self, offset):
return Point(self.x + offset, self.y)
def __rshift__(self, offset):
return Point(self.x, self.y + offset)
Arithmetic Operators
def __add__(self, other):
if hasattr(other, '__len__') and len(other) == 2:
return Point(self.x + other[0], self.y + other[1])
return None
def __sub__(self, other):
if hasattr(other, '__len__') and len(other) == 2:
dx, dy = other
return ((self.x - dx)**2 + (self.y - dy)**2)**0.5
return None
def __mul__(self, other):
return (
abs(self.x - other.x) == 1 and self.y == other.y
) or (
abs(self.y - other.y) == 1 and self.x == other.x
)
def __truediv__(self, other):
if (self.x == other.x) != (self.y == other.y):
return -1 if (self < other) < 0 or (self > other) < 0 else 1
return False
def __mod__(self, other):
return [
Point(self.x, other.y),
Point(other.x, self.y)
]
def __floordiv__(self, other):
if self.x != other.x and self.y != other.y:
p1, p2 = self % other
return (
[Point(x, self.y) for x in range(min(self.x, p1.x), max(self.x, p1.x) + 1)],
[Point(self.x, y) for y in range(min(self.y, p2.y), max(self.y, p2.y) + 1)]
)
return None