Skip to content

Commit 2066947

Browse files
committedMar 31, 2021
Rewrote the HashMap implementation (barely understand in the whole)
1 parent 188eba0 commit 2066947

File tree

3 files changed

+82
-59
lines changed

3 files changed

+82
-59
lines changed
 

‎chap05_sets_maps/hashmap.py

Lines changed: 0 additions & 59 deletions
This file was deleted.

‎chap05_sets_maps/map_hashmap.py

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
from map_hashset import HashSet
2+
3+
4+
class HashMap:
5+
"""
6+
It has many faces(names), including map, dictionary, and hash tables.
7+
8+
Status for this class:
9+
- barely understood, since I haven't even finish documented the `HashSet`.
10+
- start to work through this class after you finish the `HashSet`!
11+
- or you could read and code other implementations :)
12+
"""
13+
14+
class __KVPair:
15+
def __init__(self, key, value):
16+
self.key = key
17+
self.value = value
18+
19+
def __eq__(self, other):
20+
if type(self) != type(other):
21+
return False
22+
23+
return self.key == other.key
24+
25+
def get_key(self):
26+
return self.key
27+
28+
def get_value(self):
29+
return self.value
30+
31+
def __hash__(self):
32+
return hash(self.key)
33+
34+
def __init__(self):
35+
self.hashset = HashSet()
36+
37+
def __len__(self):
38+
return len(self.hashset)
39+
40+
def __contains__(self, item):
41+
return HashSet.__KVPair(item, None) in self.hashset
42+
43+
def __setitem__(self, key, value):
44+
self.hashset.add(HashMap.__KVPair(key, value))
45+
46+
def __getitem__(self, key):
47+
if HashMap.__KVPair(key, None) in self.hashset:
48+
value = self.hashset[HashMap.__KVPair(key, None)].get_value()
49+
50+
return value
51+
52+
raise KeyError(f"Key {str(key)} not in HashMap")
53+
54+
def __iter__(self):
55+
for item in self.hashset:
56+
yield item.get_key()
57+
58+
59+
def main():
60+
pass
61+
62+
63+
if "__main__" == __name__:
64+
main()

‎chap05_sets_maps/map_hashset.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -179,6 +179,24 @@ def __contains__(self, item):
179179

180180
return False
181181

182+
def __getitem__(self, item):
183+
"""
184+
O(?)
185+
186+
This method is specifically written for the external `HashMap` to use.
187+
The `HashSet` class itself does NOT require this method to work.
188+
"""
189+
idx = hash(item) % len(self.items)
190+
191+
while self.items[idx] is not None:
192+
if self.items[idx] == item:
193+
return self.items[idx]
194+
195+
# TODO document this
196+
idx = (idx + 1) % len(self.items)
197+
198+
return None
199+
182200
def __iter__(self):
183201
"""
184202
O(?)

0 commit comments

Comments
 (0)