-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlib.py
173 lines (124 loc) · 4.62 KB
/
lib.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
from __future__ import annotations
from itertools import chain
from typing import TYPE_CHECKING, Callable, Protocol, Self, TypeVar
if TYPE_CHECKING:
from collections.abc import Generator, Iterable, Sequence
T = TypeVar("T", infer_variance=True)
T_contra = TypeVar("T_contra", contravariant=True)
T_co = TypeVar("T_co", covariant=True)
class SupportsMaths(Protocol[T_contra, T_co]):
def __add__(self, x: T_contra, /) -> T_co: ...
def __sub__(self, x: T_contra, /) -> T_co: ...
def __mul__(self, x: T_contra, /) -> T_co: ...
class SupportsRichComparison(Protocol[T]):
def __lt__(self, other: T, /) -> bool: ...
def __gt__(self, other: T, /) -> bool: ...
N = TypeVar("N", bound=SupportsMaths)
S = TypeVar("S", bound=SupportsRichComparison)
def filter_map[X, Y](func: Callable[[X], Y | None], it: Iterable[X]) -> Generator[Y, None, None]:
"""Maps function over iterator and yields results that are not None."""
for element in it:
if (result := func(element)) is not None:
yield result
def get_limits(it: Sequence[S]) -> tuple[S, S]:
"""Get the lower and upper limits of an iterable."""
return ((x := sorted(it))[0], x[-1])
def is_intable(s: str) -> bool:
"""Return true if string input can be made an int."""
try:
int(s)
return True
except Exception as _:
return False
def is_floatable(s: str) -> bool:
"""Return true if string input can be made a float."""
try:
float(s)
return True
except Exception as _:
return False
class Peekable[T]:
def __init__(self, iterable: Iterable[T]) -> None:
self.it = iter(iterable)
def __iter__(self) -> Self:
return self
def __next__(self) -> T:
return next(self.it)
def __peek__(self) -> T | None:
it = self.it
try:
peek = next(self.it)
self.it = chain((peek,), it)
return peek
except StopIteration:
return None
def peekable(iterable: Iterable[T]) -> Peekable[T]:
return Peekable(iterable)
def peek(peekable: Peekable[T]) -> T | None:
return peekable.__peek__()
class ChunkedBy[T, U]:
def __init__(self, predicate: Callable[[T], U], iterable: Iterable[T]) -> None:
self.it = peekable(iter(iterable))
self.predicate = predicate
def __iter__(self) -> Self:
return self
def __next__(self) -> tuple[U, list[T]]:
chunk = [next(self.it)]
cat = self.predicate(chunk[0])
while peeked := peek(self.it):
if self.predicate(peeked) == cat:
chunk.append(next(self.it))
else:
break
return (cat, chunk)
def chunk_by[T, U](predicate: Callable[[T], U], iterable: Iterable[T]) -> ChunkedBy[T, U]:
return ChunkedBy(predicate, iterable)
class Point(tuple[N, ...]):
"""Subclass of tuple to support 2 or 3 dimensional points."""
__slots__ = ()
def __new__(cls, *args: N) -> Self:
return tuple.__new__(cls, args)
@property
def x(self) -> N:
return self[0]
@property
def y(self) -> N:
return self[1]
@property
def z(self) -> N:
return self[2]
def __add__(self, r: Point) -> Point: # type: ignore
if len(self) == 2:
return Point(self.x + r.x, self.y + r.y)
else:
return Point(self.x + r.x, self.y + r.y, self.z + r.z)
def __sub__(self, r: Point) -> Point:
if len(self) == 2:
return Point(self.x - r.x, self.y - r.y)
else:
return Point(self.x - r.x, self.y - r.y, self.z - r.z)
def __mul__(self, n: N) -> Point: # type: ignore
if len(self) == 2:
return Point(self.x * n, self.y * n)
else:
return Point(self.x * n, self.y * n, self.z * n)
def __lt__(self, r: Point) -> bool: # type: ignore
if len(self) == 2:
return self.x < r.x and self.y < r.y
else:
return self.x < r.x and self.y < r.y and self.z < r.z
def __le__(self, r: Point) -> bool: # type: ignore
if len(self) == 2:
return self.x <= r.x and self.y <= r.y
else:
return self.x <= r.x and self.y <= r.y and self.z <= r.z
def __gt__(self, r: Point) -> bool: # type: ignore
if len(self) == 2:
return self.x > r.x and self.y > r.y
else:
return self.x > r.x and self.y > r.y and self.z > r.z
def __ge__(self, r: Point) -> bool: # type: ignore
if len(self) == 2:
return self.x >= r.x and self.y >= r.y
else:
return self.x >= r.x and self.y >= r.y and self.z >= r.z