1- #preventing collisions in hash ord by multiplying the ordinal numbers
1+ #minimizing collisions in hash ord by multiplying the ordinal numbers, but it has some collisions
22
33def myhash (item ):
44 mult = 1
@@ -7,4 +7,75 @@ def myhash(item):
77 for ch in item :
88 hv += mult * ord (ch )
99 mult += 1
10- return hv
10+ return hv
11+
12+ for item in ('hello world' , 'world hello' , 'gello xorld' ):
13+ print (f'hash function of { item } : { myhash (item )} ' )
14+
15+ print ("========================\n " )
16+
17+ #open addressing for eliminating collisions
18+ #linear probing, quadratic probing and double hashing
19+
20+ class HashItem :
21+ def __init__ (self , key , value ):
22+ self .key = key
23+ self .value = value
24+
25+ class HashTable :
26+ def __init__ (self ):
27+ self .size = 256
28+ self .slots = [None for i in range (self .size )]
29+ self .count = 0
30+ self .MAXLOADFACTOR = 0.65 #maximum percentage of used slots for increasing the size of slots
31+
32+ #just for internal use
33+ def _hash (self , key ):
34+ hv = 0
35+ mult = 1
36+ for ch in key :
37+ hv += mult * ord (ch )
38+ mult += 1
39+ return hv % self .size
40+
41+ def put (self , key , value ):
42+ item = HashItem (key , value )
43+ h = self ._hash (key )
44+ while self .slots [h ] != None :
45+ if self .slots [h ].key == key :
46+ break
47+ h = (h + 1 ) % self .size
48+
49+ if self .slots [h ] == None :
50+ self .count += 1
51+ self .slots [h ] = item
52+ self .check_growth ()
53+
54+ def check_growth (self ):
55+ loadfactor = self .count / self .size
56+ if loadfactor > self .MAXLOADFACTOR :
57+ print ("Load factor before growing the hash table" , self .count / self .size )
58+ self .growth ()
59+ print ("Load factor after growing the hash table" , self .count / self .size )
60+
61+ def growth (self ):
62+ new_hash_table = HashTable ()
63+ new_hash_table .size = 2 * self .size
64+ new_hash_table .slots = [None for i in range (new_hash_table .size )]
65+
66+ for i in range (self .size ):
67+ if self .slots [i ] != None :
68+ new_hash_table .put (self .slots [i ].key , self .slots [i ].value )
69+
70+ self .size = new_hash_table .size
71+ self .slots = new_hash_table .slots
72+
73+ ht = HashTable ()
74+ ht .put ("good" , "eggs" )
75+ ht .put ("better" , "ham" )
76+ ht .put ("best" , "spam" )
77+ ht .put ("ad" , "do not" )
78+ ht .put ("ga" , "collide" )
79+ ht .put ("awd" , "do not" )
80+ ht .put ("add" , "do not" )
81+ ht .check_growth ()
0 commit comments