-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhashtable.py
64 lines (61 loc) · 2.17 KB
/
hashtable.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
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:
return node.data.value
node=node.next_node
if key== node.data.key:
return node.data.value
return None
def print_table(self):
print("{")
for i, val in enumerate (self.hash_table):
if val is not None:
llist_string=""
node=val
if node.next_node:
while node.next_node:
llist_string+=(
str(node.data.key)+":"+str(node.data.value)+"->"
)
node=node.next_node
llist_string+=(
str(node.data.key)+":"+str(node.data.value)+"->"
)
print(f" [{i}] {llist_string}")
else:
print(f" [{i}] {val.data.key}:{val.data.value}")
else:
print(f" [{i}] {val}")
print("}")