Computer Science

Use the hash function: h(element) = element % 10 to store the collection of numbers: [44, 121, 55, 33, 110, 77, 22, 66] in a hash table. Display the hash table created. Search if the values 11, 44, 88 and 121 are present in the hash table, and display the search results.

Python Searching

2 Likes

Answer

def h(element, hashTable):
 if (hashTable[element % 10] == key): 
    return ((element % 10) + 1) 
 else:
    return -1 
 
hashTable = [None, None, None, None, None, None, None, None, None, None]

print("We have created a hashTable of 10 positions:")
print(hashTable)
L = [44, 121, 55, 33, 110, 77, 22, 66]
print("The given list is", L[::] )

for i in range(0,len(L)): 
    hashTable[L[i]%10] = L[i]

print("The hash table contents are: " )
for i in range(0,len(hashTable)): 
 print("hashindex=", i," , value =", hashTable[i])

keys = [11, 44, 88, 121]
for key in keys:
    position = h(key,hashTable)
    if position == -1:
        print("Number",key,"is not present in the hash table")
    else:
        print("Number ",key," present at ",position, " position")
Output
We have created a hashTable of 10 positions:
[None, None, None, None, None, None, None, None, None, None]
The given list is [44, 121, 55, 33, 110, 77, 22, 66]
The hash table contents are:
hashindex= 0  , value = 110
hashindex= 1  , value = 121
hashindex= 2  , value = 22
hashindex= 3  , value = 33
hashindex= 4  , value = 44
hashindex= 5  , value = 55
hashindex= 6  , value = 66
hashindex= 7  , value = 77
hashindex= 8  , value = None
hashindex= 9  , value = None
Number 11 is not present in the hash table
Number  44  present at  5  position
Number 88 is not present in the hash table
Number  121  present at  2  position

Answered By

2 Likes


Related Questions