1
1
2
2
class HashTable (object ):
3
- def __init__ (self , size ):
4
- self .size = size
3
+ def __init__ (self ):
4
+ self .size = 8
5
5
self .slots = [None ] * self .size
6
- self .data = [None ] * self .size
7
6
8
- def put (self , key , data ):
7
+ def put (self , key ):
9
8
hashvalue = self .hashfunction (key , len (self .slots ))
10
9
11
10
if self .slots [hashvalue ] == None :
12
11
self .slots [hashvalue ] = key
13
- self .data [hashvalue ] = data
14
12
else :
15
13
if self .slots [hashvalue ] == key :
16
- self . slots [ hashvalue ] = data
14
+ pass
17
15
else :
18
16
nextslot = self .rehash (hashvalue , len (self .slots ))
19
17
while self .slots [nextslot ] != None and self .slots [nextslot ] != key :
20
18
nextslot = self .rehash (nextslot , len (self .slots ))
21
19
if self .slots [nextslot ] == None :
22
20
self .slots [nextslot ] = key
23
- self . data [ nextslot ] = data
21
+
24
22
else :
25
- self . data [ nextslot ] = data
23
+ pass
26
24
27
25
28
26
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
30
36
31
37
def rehash (self , oldhash , size ):
32
38
return (oldhash + 1 ) % size
33
39
34
40
def get (self , key ):
35
41
startslot = self .hashfunction (key , len (self .slots ))
36
- data = None
37
42
stop = False
38
43
found = False
39
44
position = startslot
40
45
41
46
while self .slots [position ] != None and not found and not stop :
42
47
if self .slots [position ] == key :
43
48
found = True
44
- data = self . data [ position ]
49
+ data = position
45
50
46
51
else :
47
52
position = self .rehash (position , len (self .slots ))
@@ -51,9 +56,16 @@ def get(self, key):
51
56
return data
52
57
53
58
if __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