-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathhashmap.py
83 lines (58 loc) · 1.81 KB
/
hashmap.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
"""
Implementing an hash map/ hash table
"""
from multiprocessing.pool import RUN
class HashMap:
def __init__(self,size):
self.size = size
self.hash_map = self.create_bucket()
def create_bucket(self):
return [[] for i in range(self.size)]
def set_val(self, key, val):
hash_key = hash(key) % self.size
bucket = self.hash_map[hash_key]
found_key = False
for index, record in enumerate(bucket):
record_key, record_val = record
if record_key == key:
found_key = True
break
if found_key:
bucket[index] = (key, val)
else:
bucket.append((key,val))
def get_val(self, key):
hash_key = hash(key) % self.size
bucket = self.hash_map[hash_key]
found_key = False
for index, record in enumerate(bucket):
record_key, record_val = record
if record_key == key:
found_key = True
break
if found_key:
return record_val
else:
return "No record found"
def delete_val(self, key):
hash_key = hash(key) % self.size
bucket = self.hash_map[hash_key]
found_key = False
for index, record in enumerate(bucket):
record_key, record_val = record
if record_key == key:
found_key = True
break
if found_key:
bucket.pop(index)
return
def __str__(self):
return "".join(str(item) for item in self.hash_map)
hash_map = HashMap(5)
hash_map.set_val('[email protected]', 'RUN')
print(hash_map)
hash_map.set_val('[email protected]', 'WING')
print(hash_map)
print(hash_map.get_val('[email protected]'))
hash_map.delete_val('[email protected]')
print(hash_map)