Below I give an example implementation of a hash table. In this implementation, I use a fixed size for the hash table. It simply reports that it is full when it reaches a certain threshold. Growing of a hash table is far less instructive than observing how the index for elements is implemented. To determine the hash value, I use the hash()
function.
Copy the code and run it on your preferred code editor.
SIZE = 13 # should be prime
FACTOR = 0.7 # limit to how many slots may be filled
PERTURB = 1 # perturbation value
hash_table = SIZE * [None]
# Stores an element in the table
def hash_store( hash_table, element, key ):
hashnum = hash( key )
while hash_table[hashnum%SIZE] != None:
if hash_table[hashnum%SIZE][0] == key: # Key already exists and the element is thus overwritten
hash_table[hashnum%SIZE] = (key, element)
return
if hash_table[hashnum%SIZE][1] == None: # Slot had an element which is now deleted, and can be overwritten
hash_table[hashnum%SIZE] = (key, element)
return
hashnum += PERTURB
if hash_table.count( None ) < (1 - FACTOR) * SIZE:
print( "Table is considered full,", key, "cannot be stored" )
return
hash_table[hashnum%SIZE] = (key, element)
# Removes an element from the table
def hash_remove( hash_table, key ):
hashnum = hash( key )
while hash_table[hashnum%SIZE] != None:
if hash_table[hashnum%SIZE][0] == key:
hash_table[hashnum%SIZE] = (key, None) # This indicates that the spot is empty, but can be part of a chain
return
hashnum += PERTURB
# Returns element if key is in table, otherwise None
def hash_find( hash_table, key ):
hashnum = hash( key )
while hash_table[hashnum%SIZE] != None:
if hash_table[hashnum%SIZE][0] == key:
if hash_table[hashnum%SIZE][1] != None:
return hash_table[hashnum%SIZE][1]
hashnum += PERTURB
return None
fruitlist = ["apple", "banana", "cherry", "durian", "fig", "grape", "lychee", "mango", "orange", "pear", "tangerine"]
for i in range( len( fruitlist ) ): # store as much fruit as possible
hash_store( hash_table, i+1, fruitlist[i] )
hash_store( hash_table, 99, "pear" ) # overwrite "pear"
hash_remove( hash_table, "apple" ) # remove "apple"
for i in range( len( fruitlist ) ):
element = hash_find( hash_table, fruitlist[i] )
if element:
print( fruitlist[i], "-", element )
else:
print( fruitlist[i], "is not in the table" )