-
Notifications
You must be signed in to change notification settings - Fork 0
/
hash_table.py
72 lines (61 loc) · 2.28 KB
/
hash_table.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
class Node:
def __init__(self, data=None, next_node=None):
self.data = data
self.next_node = next_node
class Data:
def __init__(self, key, value):
self.key = key
self.value = value
class HashTable:
def __init__(self, table_size):
self.table_size = table_size
self.hash_table = [None] * table_size
def custom_hash(self, key):
hash_value = 0
for i in key:
hash_value += ord(i)
hash_value = (hash_value * ord(i)) % self.table_size
return hash_value
def add_key_value(self, key, value):
hashed_key = self.custom_hash(key)
if self.hash_table[hashed_key] is None:
self.hash_table[hashed_key] = Node(Data(key,value), None)
else:
node = self.hash_table[hashed_key]
while node.next_node:
node = node.next_node
node.next_node = Node(Data(key,value), None)
def get_value(self, key):
hashed_key = self.custom_hash(key)
if self.hash_table[hashed_key] is not None:
node = self.hash_table[hashed_key]
if node.next_node is None:
return node.data.value
while node.next_node:
if key == node.data.key: