forked from TheAlgorithms/Python
- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhash_map.py
305 lines (254 loc) · 8.02 KB
/
hash_map.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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
"""
Hash map with open addressing.
https://en.wikipedia.org/wiki/Hash_table
Another hash map implementation, with a good explanation.
Modern Dictionaries by Raymond Hettinger
https://www.youtube.com/watch?v=p33CVV29OG8
"""
fromcollections.abcimportIterator, MutableMapping
fromdataclassesimportdataclass
fromtypingimportGeneric, TypeVar
KEY=TypeVar("KEY")
VAL=TypeVar("VAL")
@dataclass(frozen=True, slots=True)
class_Item(Generic[KEY, VAL]):
key: KEY
val: VAL
class_DeletedItem(_Item):
def__init__(self) ->None:
super().__init__(None, None)
def__bool__(self) ->bool:
returnFalse
_deleted=_DeletedItem()
classHashMap(MutableMapping[KEY, VAL]):
"""
Hash map with open addressing.
"""
def__init__(
self, initial_block_size: int=8, capacity_factor: float=0.75
) ->None:
self._initial_block_size=initial_block_size
self._buckets: list[_Item|None] = [None] *initial_block_size
assert0.0<capacity_factor<1.0
self._capacity_factor=capacity_factor
self._len=0
def_get_bucket_index(self, key: KEY) ->int:
returnhash(key) %len(self._buckets)
def_get_next_ind(self, ind: int) ->int:
"""
Get next index.
Implements linear open addressing.
>>> HashMap(5)._get_next_ind(3)
4
>>> HashMap(5)._get_next_ind(5)
1
>>> HashMap(5)._get_next_ind(6)
2
>>> HashMap(5)._get_next_ind(9)
0
"""
return (ind+1) %len(self._buckets)
def_try_set(self, ind: int, key: KEY, val: VAL) ->bool:
"""
Try to add value to the bucket.
If bucket is empty or key is the same, does insert and return True.
If bucket has another key or deleted placeholder,
that means that we need to check next bucket.
"""
stored=self._buckets[ind]
ifnotstored:
self._buckets[ind] =_Item(key, val)
self._len+=1
returnTrue
elifstored.key==key:
self._buckets[ind] =_Item(key, val)
returnTrue
else:
returnFalse
def_is_full(self) ->bool:
"""
Return true if we have reached safe capacity.
So we need to increase the number of buckets to avoid collisions.
>>> hm = HashMap(2)
>>> hm._add_item(1, 10)
>>> hm._add_item(2, 20)
>>> hm._is_full()
True
>>> HashMap(2)._is_full()
False
"""
limit=len(self._buckets) *self._capacity_factor
returnlen(self) >=int(limit)
def_is_sparse(self) ->bool:
"""Return true if we need twice fewer buckets when we have now."""
iflen(self._buckets) <=self._initial_block_size:
returnFalse
limit=len(self._buckets) *self._capacity_factor/2
returnlen(self) <limit
def_resize(self, new_size: int) ->None:
old_buckets=self._buckets
self._buckets= [None] *new_size
self._len=0
foriteminold_buckets:
ifitem:
self._add_item(item.key, item.val)
def_size_up(self) ->None:
self._resize(len(self._buckets) *2)
def_size_down(self) ->None:
self._resize(len(self._buckets) //2)
def_iterate_buckets(self, key: KEY) ->Iterator[int]:
ind=self._get_bucket_index(key)
for_inrange(len(self._buckets)):
yieldind
ind=self._get_next_ind(ind)
def_add_item(self, key: KEY, val: VAL) ->None:
"""
Try to add 3 elements when the size is 5
>>> hm = HashMap(5)
>>> hm._add_item(1, 10)
>>> hm._add_item(2, 20)
>>> hm._add_item(3, 30)
>>> hm
HashMap(1: 10, 2: 20, 3: 30)
Try to add 3 elements when the size is 5
>>> hm = HashMap(5)
>>> hm._add_item(-5, 10)
>>> hm._add_item(6, 30)
>>> hm._add_item(-7, 20)
>>> hm
HashMap(-5: 10, 6: 30, -7: 20)
Try to add 3 elements when size is 1
>>> hm = HashMap(1)
>>> hm._add_item(10, 13.2)
>>> hm._add_item(6, 5.26)
>>> hm._add_item(7, 5.155)
>>> hm
HashMap(10: 13.2)
Trying to add an element with a key that is a floating point value
>>> hm = HashMap(5)
>>> hm._add_item(1.5, 10)
>>> hm
HashMap(1.5: 10)
5. Trying to add an item with the same key
>>> hm = HashMap(5)
>>> hm._add_item(1, 10)
>>> hm._add_item(1, 20)
>>> hm
HashMap(1: 20)
"""
forindinself._iterate_buckets(key):
ifself._try_set(ind, key, val):
break
def__setitem__(self, key: KEY, val: VAL) ->None:
"""
1. Changing value of item whose key is present
>>> hm = HashMap(5)
>>> hm._add_item(1, 10)
>>> hm.__setitem__(1, 20)
>>> hm
HashMap(1: 20)
2. Changing value of item whose key is not present
>>> hm = HashMap(5)
>>> hm._add_item(1, 10)
>>> hm.__setitem__(0, 20)
>>> hm
HashMap(0: 20, 1: 10)
3. Changing the value of the same item multiple times
>>> hm = HashMap(5)
>>> hm._add_item(1, 10)
>>> hm.__setitem__(1, 20)
>>> hm.__setitem__(1, 30)
>>> hm
HashMap(1: 30)
"""
ifself._is_full():
self._size_up()
self._add_item(key, val)
def__delitem__(self, key: KEY) ->None:
"""
>>> hm = HashMap(5)
>>> hm._add_item(1, 10)
>>> hm._add_item(2, 20)
>>> hm._add_item(3, 30)
>>> hm.__delitem__(3)
>>> hm
HashMap(1: 10, 2: 20)
>>> hm = HashMap(5)
>>> hm._add_item(-5, 10)
>>> hm._add_item(6, 30)
>>> hm._add_item(-7, 20)
>>> hm.__delitem__(-5)
>>> hm
HashMap(6: 30, -7: 20)
# Trying to remove a non-existing item
>>> hm = HashMap(5)
>>> hm._add_item(1, 10)
>>> hm._add_item(2, 20)
>>> hm._add_item(3, 30)
>>> hm.__delitem__(4)
Traceback (most recent call last):
...
KeyError: 4
"""
forindinself._iterate_buckets(key):
item=self._buckets[ind]
ifitemisNone:
raiseKeyError(key)
ifitemis_deleted:
continue
ifitem.key==key:
self._buckets[ind] =_deleted
self._len-=1
break
ifself._is_sparse():
self._size_down()
def__getitem__(self, key: KEY) ->VAL:
"""
Returns the item at the given key
>>> hm = HashMap(5)
>>> hm._add_item(1, 10)
>>> hm.__getitem__(1)
10
>>> hm = HashMap(5)
>>> hm._add_item(10, -10)
>>> hm._add_item(20, -20)
>>> hm.__getitem__(20)
-20
>>> hm = HashMap(5)
>>> hm._add_item(-1, 10)
>>> hm.__getitem__(-1)
10
"""
forindinself._iterate_buckets(key):
item=self._buckets[ind]
ifitemisNone:
break
ifitemis_deleted:
continue
ifitem.key==key:
returnitem.val
raiseKeyError(key)
def__len__(self) ->int:
"""
Returns the number of items present in hashmap
>>> hm = HashMap(5)
>>> hm._add_item(1, 10)
>>> hm._add_item(2, 20)
>>> hm._add_item(3, 30)
>>> hm.__len__()
3
>>> hm = HashMap(5)
>>> hm.__len__()
0
"""
returnself._len
def__iter__(self) ->Iterator[KEY]:
yieldfrom (item.keyforiteminself._bucketsifitem)
def__repr__(self) ->str:
val_string=", ".join(
f"{item.key}: {item.val}"foriteminself._bucketsifitem
)
returnf"HashMap({val_string})"
if__name__=="__main__":
importdoctest
doctest.testmod()