-
Notifications
You must be signed in to change notification settings - Fork 17
/
sequentially-ordinal-rank-tracker.py
71 lines (47 loc) · 1.81 KB
/
sequentially-ordinal-rank-tracker.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
import heapq
from dataclasses import dataclass
from typing import List, Tuple
@dataclass
class Name:
value: str
def __lt__(self, other: object) -> bool:
if not isinstance(other, Name):
raise ValueError()
return self.value < other.value
def __gt__(self, other: object) -> bool:
if not isinstance(other, Name):
raise ValueError()
return self.value > other.value
@dataclass
class NameInversed:
value: str
def __lt__(self, other: object) -> bool:
if not isinstance(other, NameInversed):
raise ValueError()
return self.value > other.value
def __gt__(self, other: object) -> bool:
if not isinstance(other, NameInversed):
raise ValueError()
return self.value < other.value
class SORTracker:
def __init__(self) -> None:
self._left_heap: List[Tuple[int, NameInversed]] = []
self._right_heap: List[Tuple[int, Name]] = []
self._pos = 0
def _inverse_string(self, name: str) -> str:
return "".join(chr(ord("a") + ord("z") - ord(char)) for char in name)
def _balance(self) -> None:
if len(self._left_heap) > self._pos + 1:
score, name_inversed = heapq.heappop(self._left_heap)
heapq.heappush(self._right_heap, (-score, Name(name_inversed.value)))
elif len(self._left_heap) < self._pos + 1 and self._right_heap:
score, name = heapq.heappop(self._right_heap)
heapq.heappush(self._left_heap, (-score, NameInversed(name.value)))
def add(self, name: str, score: int) -> None:
heapq.heappush(self._left_heap, (score, NameInversed(name)))
self._balance()
def get(self) -> str:
_, name = self._left_heap[0]
self._pos += 1
self._balance()
return name.value