-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlook_up.py
72 lines (48 loc) · 1.77 KB
/
look_up.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
import bisect
from typing import Any, Protocol, Mapping, overload, Iterable, Sequence, Iterator
class Comparable(Protocol):
"""
This protocol defines what methods are required for a class to be considered comparable.
"""
def __eq__(self, other: Any) -> bool:
...
def __ne__(self, other: Any) -> bool:
...
def __lt__(self, other: Any) -> bool:
...
def __le__(self, other: Any) -> bool:
...
def __gt__(self, other: Any) -> bool:
...
def __ge__(self, other: Any) -> bool:
...
BaseMapping = Mapping[Comparable, Any]
class LookUp:
"""Our custom dictionary-like class that stores key-value pairs in sorted order."""
@overload
def __init__(self, source: Iterable[tuple[Comparable, Any]]) -> None:
...
@overload
def __init__(self, source: BaseMapping) -> None:
...
def __init__(self, source: Iterable[tuple[Comparable, Any]] | BaseMapping | None = None) -> None:
sorted_pairs: Sequence[tuple[Comparable, Any]]
if isinstance(source, Mapping):
sorted_pairs = sorted(source.items())
elif isinstance(source, Sequence):
sorted_pairs = sorted(source)
else:
sorted_pairs = []
self.keys = [pair[0] for pair in sorted_pairs]
self.values = [pair[1] for pair in sorted_pairs]
def __len__(self) -> int:
return len(self.keys)
def __iter__(self) -> Iterator[Comparable]:
return iter(self.keys)
def __contains__(self, key: object) -> bool:
return key in self.keys
def __getitem__(self, key: Comparable) -> Any:
index = bisect.bisect_left(self.keys, key)
if key != self.keys[index]:
raise KeyError(key)
return self.values[index]