-
Notifications
You must be signed in to change notification settings - Fork 32
/
Copy pathDictionary.py
48 lines (35 loc) · 1.14 KB
/
Dictionary.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
from collections import defaultdict
from typing import Generic, Optional, TypeVar
V = TypeVar("V")
class Dictionary(Generic[V]):
"""获取对象唯一标识的字典."""
__slots__ = "_valueToId", "_idToValue"
def __init__(self):
self._valueToId = dict()
self._idToValue = []
def id(self, value: V) -> int:
res = self._valueToId.get(value, None)
if res is not None:
return res
id_ = len(self._idToValue)
self._idToValue.append(value)
self._valueToId[value] = id_
return id_
def value(self, id_: int) -> Optional[V]:
if id_ < 0 or id_ >= len(self._idToValue):
return None
return self._idToValue[id_]
def __len__(self) -> int:
return len(self._idToValue)
def __contains__(self, v: V) -> bool:
return v in self._valueToId
if __name__ == "__main__":
d = Dictionary[str]()
print(d.id("a"))
print(d.id("b"))
print(d.id("a"))
print(d.value(0))
print(d.value(1))
print(d.value(2))
print(len(d))
id = defaultdict(lambda: len(id))