-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhash-table.py
More file actions
43 lines (37 loc) · 1.17 KB
/
hash-table.py
File metadata and controls
43 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
class HashTable:
def __init__(self, size=10):
self.size = size
self.table = [[] for _ in range(size)]
def _hash(self, key):
return hash(key) % self.size
def insert(self, key, value):
index = self._hash(key)
for pair in self.table[index]:
if pair[0] == key:
pair[1] = value
return
self.table[index].append([key, value])
def get(self, key):
index = self._hash(key)
for pair in self.table[index]:
if pair[0] == key:
return pair[1]
return(f"Key {key} not found")
def remove(self, key):
index = self._hash(key)
for i, pair in enumerate(self.table[index]):
if pair[0] == key:
del self.table[index][i]
return
return(f"Key {key} not found")
# Example on how to use it
ht = HashTable(size=5)
ht.insert("name", "Maria")
ht.insert("age", 25)
ht.insert("city", "Sao Paulo")
ht.insert("name", "Carlos")
print(f"Hash Table: {ht}")
print(f"Get 'name': {ht.get('name')}")
print(f"Get 'city': {ht.get('city')}")
ht.remove("age")
print(f"Hash Table after removing 'age': {ht}")