-
Notifications
You must be signed in to change notification settings - Fork 0
/
chain_hash_map.py
52 lines (46 loc) · 2 KB
/
chain_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
# Copyright 2013, Michael H. Goldwasser
#
# Developed for use with the book:
#
# Data Structures and Algorithms in Python
# Michael T. Goodrich, Roberto Tamassia, and Michael H. Goldwasser
# John Wiley & Sons, 2013
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from hash_map_base import HashMapBase
from unsorted_table_map import UnsortedTableMap
class ChainHashMap(HashMapBase):
"""Hash map implemented with separate chaining for collision resolution."""
def _bucket_getitem(self, j, k):
bucket = self._table[j]
if bucket is None:
raise KeyError('Key Error: ' + repr(k)) # no match found
return bucket[k] # may raise KeyError
def _bucket_setitem(self, j, k, v):
if self._table[j] is None:
self._table[j] = UnsortedTableMap() # bucket is new to the table
oldsize = len(self._table[j])
self._table[j][k] = v
if len(self._table[j]) > oldsize: # key was new to the table
self._n += 1 # increase overall map size
def _bucket_delitem(self, j, k):
bucket = self._table[j]
if bucket is None:
raise KeyError('Key Error: ' + repr(k)) # no match found
del bucket[k] # may raise KeyError
def __iter__(self):
for bucket in self._table:
if bucket is not None: # a nonempty slot
for key in bucket:
yield key