Introduction:
This Python code demonstrates the use of a hash table to perform a search for an element using a hash function. A hash table is a data structure that stores key-value pairs and provides fast retrieval of values based on their keys. In this example, we use a simple hash function to map keys to positions in the hash table.
Code:
# Function to check if a key is present in the hash table
def hashFind(key, hashTable):
if (hashTable[key % 10] == key): # key is present
return key % 10 + 1 # return the position
else:
return None # key is not present
# end of function
# Create hashTable with 10 empty positions
hashTable = [None, None, None, None, None, None, None, None, None, None]
print("We have created a hashTable of 10 positions:")
print(hashTable)
# Given list
L = [34, 16, 2, 93, 80, 77, 51]
print("The given list is", L)
# Apply the hash function and populate the hash table
for i in range(0, len(L)):
hashTable[L[i] % 10] = L[i]
# Print the contents of the hash table
print("The hash table contents are:")
for i in range(0, len(hashTable)):
print("hashindex=", i, ", value =", hashTable[i])
# Ask the user to enter the number they want to search for
key = int(input("Enter the number to be searched:"))
position = hashFind(key, hashTable)
# Check the result of the hashFind function and print appropriate messages
if position is None:
print("Number", key, "is not present in the hash table")
else:
print("Number", key, "present at", position, "position")
Logic:
- The hashFind function takes a key and a hash table as its parameters.
- It calculates the hash index for the key using the modulo operation (key % 10) to map the key to a position in the hash table.
- It then checks if the key at the calculated hash index in the hash table matches the given key.
- If a match is found, the function returns the position (hash index + 1) of the key in the hash table.
- If no match is found, the function returns None to indicate that the key is not present in the hash table.
- The user is prompted to enter a list of numbers, and the hash table is populated using the hash function.
- The contents of the hash table are printed.
- The user is asked to enter the number they want to search for.
- The hashFind function is called to search for the user-provided key in the hash table.
- The program outputs whether the key is present in the hash table and its position if found.
Output:
>>We have created a hashTable of 10 positions:
>>[None, None, None, None, None, None, None, None, None, None]
>>The given list is [34, 16, 2, 93, 80, 77, 51]
>>The hash table contents are: hashindex= 0 , value = 80
>>hashindex= 1 , value = 51
>>hashindex= 2 , value = 2
>>hashindex= 3 , value = 93
>>hashindex= 4 , value = 34
>>hashindex= 5 , value = 16
>>hashindex= 6 , value = 77
>>hashindex= 7 , value = None
>>hashindex= 8 , value = None
>>hashindex= 9 , value = None
>>Enter the number to be searched: 93
>>Number 93 present at 4 position