From 5fd442c3bba6b4c63facb6bd89ecc3a9736e1c8d Mon Sep 17 00:00:00 2001 From: Tom van der Lee Date: Sat, 17 Dec 2022 17:17:54 +0100 Subject: Added some utilities --- aoc/datastructures.py | 27 +++++++++++++++++++++++++++ aoc/decorators.py | 17 +++++++++++++++++ 2 files changed, 44 insertions(+) create mode 100644 aoc/datastructures.py create mode 100644 aoc/decorators.py (limited to 'aoc') diff --git a/aoc/datastructures.py b/aoc/datastructures.py new file mode 100644 index 0000000..c49f564 --- /dev/null +++ b/aoc/datastructures.py @@ -0,0 +1,27 @@ +# -*- coding: utf-8 -*- +from collections import namedtuple + + +class Coordinate(namedtuple("Coordinate", ["x", "y"])): + def __sub__(self, other: "Coordinate"): + return Coordinate(self.x - other.x, self.y - other.y) + + def __add__(self, other: "Coordinate"): + return Coordinate(self.x + other.x, self.y + other.y) + + def manhattan_distance(self, other: "Coordinate"): + return abs(self.x - other.x) + abs(self.y - other.y) + + @property + def polarity_x(self): + try: + return abs(self.x) / self.x + except ZeroDivisionError: + return 0 + + @property + def polarity_y(self): + try: + return abs(self.y) / self.y + except ZeroDivisionError: + return 0 diff --git a/aoc/decorators.py b/aoc/decorators.py new file mode 100644 index 0000000..a31993a --- /dev/null +++ b/aoc/decorators.py @@ -0,0 +1,17 @@ +# -*- coding: utf-8 -*- +from functools import wraps +from typing import Iterator, TypeVar, Callable + +T = TypeVar("T") + + +def infinite_generator(func: Callable[[...], Iterator[T]]): + @wraps(func) + def wrapper(*args, **kwargs): + items = list(func(*args, **kwargs)) + + while True: + for item in items: + yield item + + return wrapper -- cgit v1.2.3