1+ class Node :
2+ def __init__ (self , key = None , value = None ):
3+ self .key = key
4+ self .value = value
5+ self .next = None
6+
7+ class SinglyLinkedList :
8+ def __init__ (self ):
9+ self .tail = None
10+ self .head = None
11+
12+ def append (self , key , value ):
13+ new_node = Node (key , value )
14+ if self .tail is None :
15+ self .head = new_node
16+ self .tail = new_node
17+ else :
18+ self .tail .next = new_node
19+ self .tail = new_node
20+
21+ def traverse (self , key ):
22+ current = self .head
23+ while current :
24+ print ("\" " , current .key , "--" , current .value , "\" " )
25+ current = current .next
26+
27+ def search (self , key ):
28+ current = self .head
29+ while current :
30+ if current .key == key :
31+ print ("\" Record found:" , current .key , "-" , current .value , "\" " )
32+ return True
33+ current = current .next
34+ return False
35+
36+
37+ class HashTableChaining :
38+ def __init__ (self ):
39+ self .size = 6
40+ self .slots = [None for i in range (self .size )]
41+ for x in range (self .size ) :
42+ self .slots [x ] = SinglyLinkedList ()
43+
44+ def _hash (self , key ):
45+ mult = 1
46+ hv = 0
47+ for ch in key :
48+ hv += mult * ord (ch )
49+ mult += 1
50+ return hv % self .size
51+
52+ def put (self , key , value ):
53+ node = Node (key , value )
54+ h = self ._hash (key )
55+ self .slots [h ].append (key , value )
56+
57+ def get (self , key ):
58+ h = self ._hash (key )
59+ v = self .slots [h ].search (key )
60+
61+ def printHashTable (self ) :
62+ print ("Hash table is :- \n " )
63+ print ("Index \t \t Values\n " )
64+ for x in range (self .size ) :
65+ print (x ,end = "\t \n " )
66+ self .slots [x ].traverse ()
67+
68+
69+ ht = HashTableChaining ()
70+ ht .put ("good" , "eggs" )
71+ ht .put ("better" , "ham" )
72+ ht .put ("best" , "spam" )
73+ ht .put ("ad" , "do not" )
74+ ht .put ("ga" , "collide" )
75+ ht .put ("awd" , "do not" )
76+
77+ ht .printHashTable ()
0 commit comments