Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit c81cc26

Browse files
isidroasCjkjvfnbyMaximSmolskiy
authored
Improve hash map (TheAlgorithms#12678)
* Mutable _Item * document falsy item * resize_down: expected test result * resize_down: actual result This is a problem since it causes rapid cycling * improve comment about falsy item Co-authored-by: Andrey <Cjkjvfnby@gmail.com> * fix long line * Update hash_map.py * Update hash_map.py --------- Co-authored-by: Andrey <Cjkjvfnby@gmail.com> Co-authored-by: Maxim Smolskiy <mithridatus@mail.ru>
1 parent ca445f5 commit c81cc26

File tree

1 file changed

+26
-4
lines changed

1 file changed

+26
-4
lines changed

data_structures/hashing/hash_map.py

Lines changed: 26 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616
VAL = TypeVar("VAL")
1717

1818

19-
@dataclass(frozen=True, slots=True)
19+
@dataclass(slots=True)
2020
class _Item(Generic[KEY, VAL]):
2121
key: KEY
2222
val: VAL
@@ -72,16 +72,17 @@ def _try_set(self, ind: int, key: KEY, val: VAL) -> bool:
7272
7373
If bucket is empty or key is the same, does insert and return True.
7474
75-
If bucket has another key or deleted placeholder,
76-
that means that we need to check next bucket.
75+
If bucket has another key that means that we need to check next bucket.
7776
"""
7877
stored = self._buckets[ind]
7978
if not stored:
79+
# A falsy item means that bucket was never used (None)
80+
# or was deleted (_deleted).
8081
self._buckets[ind] = _Item(key, val)
8182
self._len += 1
8283
return True
8384
elif stored.key == key:
84-
self._buckets[ind] = _Item(key, val)
85+
stored.val = val
8586
return True
8687
else:
8788
return False
@@ -228,6 +229,27 @@ def __delitem__(self, key: KEY) -> None:
228229
Traceback (most recent call last):
229230
...
230231
KeyError: 4
232+
233+
# Test resize down when sparse
234+
## Setup: resize up
235+
>>> hm = HashMap(initial_block_size=100, capacity_factor=0.75)
236+
>>> len(hm._buckets)
237+
100
238+
>>> for i in range(75):
239+
... hm[i] = i
240+
>>> len(hm._buckets)
241+
100
242+
>>> hm[75] = 75
243+
>>> len(hm._buckets)
244+
200
245+
246+
## Resize down
247+
>>> del hm[75]
248+
>>> len(hm._buckets)
249+
200
250+
>>> del hm[74]
251+
>>> len(hm._buckets)
252+
100
231253
"""
232254
for ind in self._iterate_buckets(key):
233255
item = self._buckets[ind]

0 commit comments

Comments
 (0)