Skip to content
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
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>
  • Loading branch information
3 people authored May 22, 2025
commit c81cc269962b346420b9e551782bd836dedb4528
30 changes: 26 additions & 4 deletions data_structures/hashing/hash_map.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
VAL = TypeVar("VAL")


@dataclass(frozen=True, slots=True)
@dataclass(slots=True)
class _Item(Generic[KEY, VAL]):
key: KEY
val: VAL
Expand Down Expand Up @@ -72,16 +72,17 @@ def _try_set(self, ind: int, key: KEY, val: VAL) -> bool:

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.
If bucket has another key that means that we need to check next bucket.
"""
stored = self._buckets[ind]
if not stored:
# A falsy item means that bucket was never used (None)
# or was deleted (_deleted).
self._buckets[ind] = _Item(key, val)
self._len += 1
return True
elif stored.key == key:
self._buckets[ind] = _Item(key, val)
stored.val = val
return True
else:
return False
Expand Down Expand Up @@ -228,6 +229,27 @@ def __delitem__(self, key: KEY) -> None:
Traceback (most recent call last):
...
KeyError: 4

# Test resize down when sparse
## Setup: resize up
>>> hm = HashMap(initial_block_size=100, capacity_factor=0.75)
>>> len(hm._buckets)
100
>>> for i in range(75):
... hm[i] = i
>>> len(hm._buckets)
100
>>> hm[75] = 75
>>> len(hm._buckets)
200

## Resize down
>>> del hm[75]
>>> len(hm._buckets)
200
>>> del hm[74]
>>> len(hm._buckets)
100
"""
for ind in self._iterate_buckets(key):
item = self._buckets[ind]
Expand Down