diff options
Diffstat (limited to 'aoc')
| -rw-r--r-- | aoc/datastructures.py | 27 | ||||
| -rw-r--r-- | aoc/decorators.py | 17 |
2 files changed, 44 insertions, 0 deletions
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 @@ | |||
| 1 | # -*- coding: utf-8 -*- | ||
| 2 | from collections import namedtuple | ||
| 3 | |||
| 4 | |||
| 5 | class Coordinate(namedtuple("Coordinate", ["x", "y"])): | ||
| 6 | def __sub__(self, other: "Coordinate"): | ||
| 7 | return Coordinate(self.x - other.x, self.y - other.y) | ||
| 8 | |||
| 9 | def __add__(self, other: "Coordinate"): | ||
| 10 | return Coordinate(self.x + other.x, self.y + other.y) | ||
| 11 | |||
| 12 | def manhattan_distance(self, other: "Coordinate"): | ||
| 13 | return abs(self.x - other.x) + abs(self.y - other.y) | ||
| 14 | |||
| 15 | @property | ||
| 16 | def polarity_x(self): | ||
| 17 | try: | ||
| 18 | return abs(self.x) / self.x | ||
| 19 | except ZeroDivisionError: | ||
| 20 | return 0 | ||
| 21 | |||
| 22 | @property | ||
| 23 | def polarity_y(self): | ||
| 24 | try: | ||
| 25 | return abs(self.y) / self.y | ||
| 26 | except ZeroDivisionError: | ||
| 27 | 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 @@ | |||
| 1 | # -*- coding: utf-8 -*- | ||
| 2 | from functools import wraps | ||
| 3 | from typing import Iterator, TypeVar, Callable | ||
| 4 | |||
| 5 | T = TypeVar("T") | ||
| 6 | |||
| 7 | |||
| 8 | def infinite_generator(func: Callable[[...], Iterator[T]]): | ||
| 9 | @wraps(func) | ||
| 10 | def wrapper(*args, **kwargs): | ||
| 11 | items = list(func(*args, **kwargs)) | ||
| 12 | |||
| 13 | while True: | ||
| 14 | for item in items: | ||
| 15 | yield item | ||
| 16 | |||
| 17 | return wrapper | ||
