-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathHashTable.py
More file actions
68 lines (48 loc) · 2.02 KB
/
Copy pathHashTable.py
File metadata and controls
68 lines (48 loc) · 2.02 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
class HashTable:
def __init__(self):
# based on the load factor we may change the size of the underlying
# data structure (dynamic resizing)
self.capacity = 10
self.keys = [None]*self.capacity
self.values = [None] * self.capacity
def insert(self, key, data):
# we have to find a valid location for the value (data)
index = self.hash_function(key)
# there may be collisions which means that the index is already occupied
# while we do not find an empty array slot
while self.keys[index] is not None:
# sometimes we have to update the value if the key is already present
if self.keys[index] == key:
self.values[index] = data
return
# do linear probing (try the next slot in the array)
# because we may increment the index such that we are outside the range
# of the underlying list
index = (index+1) % self.capacity
# we have found the valid slot for the item
# so we have to insert the data
self.keys[index] = key
self.values[index] = data
def get(self, key):
# we have to find a valid location for the value (data)
index = self.hash_function(key)
while self.keys[index] is not None:
# this is when we find the item we are looking for
if self.keys[index] == key:
return self.values[index]
index = (index + 1) % self.capacity
# the given key value pair with key does not exist in the hashtable
return None
# hash value (index of the array) based on the key
def hash_function(self, key):
hash_sum = 0
for letter in key:
hash_sum = hash_sum + ord(letter)
return hash_sum % self.capacity
if __name__ == '__main__':
table = HashTable()
table.insert('Adam', 23)
table.insert('Kevin', 45)
table.insert('Daniel', 34)
table.insert('Daniel', 33)
print(table.get('Daniel'))