-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
54 lines (38 loc) · 1.1 KB
/
main.py
File metadata and controls
54 lines (38 loc) · 1.1 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
46
47
48
49
50
51
52
53
54
class HashTable:
def __init__(self):
self.collection = {}
def hash(self, value):
return sum([ord(char) for char in value])
def add(self, key, value):
hash_value = self.hash(key)
if hash_value in self.collection:
self.collection[hash_value][key] = value
else:
self.collection[hash_value] = {key: value}
def remove(self, key):
hash_value = self.hash(key)
if hash_value in self.collection and key in self.collection[hash_value]:
self.collection[hash_value].pop(key)
def lookup(self, key):
hash_value = self.hash(key)
if hash_value in self.collection and key in self.collection[hash_value]:
return self.collection[hash_value][key]
return None
# ========================
# Example usage
# ========================
# ht = HashTable()
# ht.add("name", "John")
# ht.add("age", 30)
# ht.add("city", "LA")
# print(ht.lookup("name"))
# print(ht.lookup("age"))
# print(ht.lookup("country"))
# ht.remove("age")
# print(ht.lookup("age"))
# # Handling collisions
# ht.add("abc", 123)
# ht.add("cba", 456)
# print(ht.lookup("abc"))
# print(ht.lookup("cba"))
# print(ht.collection)