11
22class HashTable (object ):
3- def __init__ (self , size ):
4- self .size = size
3+ def __init__ (self ):
4+ self .size = 8
55 self .slots = [None ] * self .size
6- self .data = [None ] * self .size
76
8- def put (self , key , data ):
7+ def put (self , key ):
98 hashvalue = self .hashfunction (key , len (self .slots ))
109
1110 if self .slots [hashvalue ] == None :
1211 self .slots [hashvalue ] = key
13- self .data [hashvalue ] = data
1412 else :
1513 if self .slots [hashvalue ] == key :
16- self . slots [ hashvalue ] = data
14+ pass
1715 else :
1816 nextslot = self .rehash (hashvalue , len (self .slots ))
1917 while self .slots [nextslot ] != None and self .slots [nextslot ] != key :
2018 nextslot = self .rehash (nextslot , len (self .slots ))
2119 if self .slots [nextslot ] == None :
2220 self .slots [nextslot ] = key
23- self . data [ nextslot ] = data
21+ 2422 else :
25- self . data [ nextslot ] = data
23+ pass
2624
2725
2826 def hashfunction (self , key , size ):
29- return key % size
27+ consonants = 0
28+ digits = 0
29+ for x in key :
30+ if x .isdigit ():
31+ digits += int (x )
32+ else :
33+ consonants += ord (x )
34+ 35+ return (consonants - digits ) % 8
3036
3137 def rehash (self , oldhash , size ):
3238 return (oldhash + 1 ) % size
3339
3440 def get (self , key ):
3541 startslot = self .hashfunction (key , len (self .slots ))
36- data = None
3742 stop = False
3843 found = False
3944 position = startslot
4045
4146 while self .slots [position ] != None and not found and not stop :
4247 if self .slots [position ] == key :
4348 found = True
44- data = self . data [ position ]
49+ data = position
4550
4651 else :
4752 position = self .rehash (position , len (self .slots ))
@@ -51,9 +56,16 @@ def get(self, key):
5156 return data
5257
5358if __name__ == "__main__" :
54- h = HashTable (5 )
55- for i in range (5 ):
56- h .put (i , i * 2 )
57- 58- for i in range (5 ):
59- print (h .get (i ))
59+ h = HashTable ()
60+ h .put ("3C2SE11" )
61+ h .put ("8B41" )
62+ h .put ("DE4Z23DA" )
63+ h .put ("J4" )
64+ h .put ("6GOJE45" )
65+ print ("Position of 3C2SE11:" ,h .get ("3C2SE11" ))
66+ print ("Position of 8B41:" ,h .get ("8B41" ))
67+ print ("Position of DE4Z23DA:" ,h .get ("DE4Z23DA" ))
68+ print ("Position of J4:" ,h .get ("J4" ))
69+ print ("Position of 6GOJE45:" ,h .get ("6GOJE45" ))
70+ 71+
0 commit comments