-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHashMap.py
More file actions
45 lines (37 loc) · 1.17 KB
/
Copy pathHashMap.py
File metadata and controls
45 lines (37 loc) · 1.17 KB
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
import ctypes
class HashMap:
def __init__(self, arr_size=10):
self.array_size = arr_size
self.array = (ctypes.py_object * self.array_size)()
for idx in range(self.array_size):
self.array[idx] = None
def _hash(self, key):
return hash(key) % self.array_size
def put(self, key, value):
index = self._hash(key)
if self.array[index] is None:
self.array[index] = []
bucket = self.array[index]
for i, (k, v) in enumerate(bucket):
if k == key:
bucket[i] = (key, value)
break
else:
bucket.append((key, value))
def get(self, key):
index = self._hash(key)
bucket = self.array[index]
if bucket is not None:
for k, v in bucket:
if k == key:
return v
return None
def remove(self, key):
index = self._hash(key)
bucket = self.array[index]
if bucket is not None:
for i, (k, v) in enumerate(bucket):
if k == key:
del bucket[i]
return
raise KeyError(key)