@@ -30,15 +30,19 @@ def __init__(self):
3030 self .data = [None ] * self .size
3131
3232 def put (self , key , data ):
33- hashvalue = self .hashfunction (key , len ( self .slots ) )
33+ hashvalue = self .hashfunction (key , self .size )
3434
3535 if self .slots [hashvalue ] == None :
3636 self .slots [hashvalue ] = key
3737 self .data [hashvalue ] = data
3838 else :
39- if self .slots [hashvalue ] == key :
40- self .data [hashvalue ] = data
39+ if self .slots [hashvalue ] == key :
40+ self .data [hashvalue ] = data # 替换相同索引对应的项目
4141 else :
42+ if None not in self .slots and key not in self .slots :
43+ # 判断hash是否已经满了, 必须添加key not in self.slots, 否则修改已有hash值会直接返回-1
44+ print ('sorry, there is not enough slots for you!' )
45+ return - 1
4246 nextslot = self .rehash (hashvalue , len (self .slots ))
4347 while self .slots [nextslot ] != None and self .slots [nextslot ] != key :
4448 nextslot = self .rehash (nextslot , len (self .slots ))
@@ -48,6 +52,7 @@ def put(self, key, data):
4852 self .data [nextslot ] = data
4953 else :
5054 self .data [nextslot ] = data
55+
5156 def hashfunction (self , key , size ):
5257 return key % size
5358
@@ -79,14 +84,21 @@ def __setitem__(self, key, data):
7984
8085H = HashTable ()
8186H [54 ] = 'cat'
82- H [26 ]= "dog"
83- H [93 ]= "lion"
84- H [17 ]= "tiger"
85- H [77 ]= "bird"
86- H [31 ]= "cow"
87- H [44 ]= "goat"
88- H [55 ]= "pig"
89- H [20 ]= "chicken"
87+ H [26 ] = "dog"
88+ H [93 ] = "lion"
89+ H [17 ] = "tiger"
90+ H [77 ] = "bird"
91+ H [31 ] = "cow"
92+ H [44 ] = "goat"
93+ H [55 ] = "pig"
94+ H [20 ] = "chicken"
95+ print (H [20 ])
9096print (H .slots )
9197print (H .data )
92- print (H [99 ])
98+ print (H [99 ])
99+ H [21 ] = "elephant"
100+ H [22 ] = "sheep"
101+ H [23 ] = "fish"
102+ print (H .data )
103+ H [20 ] = 'monkey'
104+ print (H .data )
0 commit comments