class HashTable:
def __init__(self, size):
self.size = size
self.keys = [None] * size
self.values = [None] * size
def hash_function(self, key):
return hash(key) % self.size
def insert(self, key, value):
index = self.hash_function(key)
probe = 1
while self.keys[index] is not None:
if self.keys[index] == key:
# Key already exists, update the value
self.values[index] = value
return
# Quadratic probing
index = (index + probe**2) % self.size
probe += 1
self.keys[index] = key
self.values[index] = value
def search(self, key):
index = self.hash_function(key)
probe = 1
comparisons = 0
while self.keys[index] is not None:
comparisons += 1
if self.keys[index] == key:
return self.values[index], comparisons
# Quadratic probing
index = (index + probe**2) % self.size
probe += 1
return None, comparisons
def main():
size = int(input("Enter the size of the hash table: "))
telephone_book = HashTable(size)
while True:
print("\n----- Telephone Book Database Menu -----")
print("1. Add a telephone number")
print("2. Search for a telephone number")
print("3. Calculate number of comparisons for a set of telephone numbers")
print("4. Exit")
choice = input("Enter your choice (1-4): ")
if choice == '1':
name = input("Enter the client's name: ")
number = input("Enter the telephone number: ")
telephone_book.insert(name, number)
print("Telephone number added successfully.")
elif choice == '2':
name = input("Enter the client's name to search: ")
result, comparisons = telephone_book.search(name)
if result is not None:
print("Telephone number found:", result)
else:
print("Telephone number not found.")
print("Number of comparisons:", comparisons)
elif choice == '3':
set_size = int(input("Enter the number of telephone numbers to search:
"))
telephone_numbers = []
for i in range(set_size):
number = input("Enter telephone number {i+1}: ")
telephone_numbers.append(number)
total_comparisons = 0
for number in telephone_numbers:
_, comparisons = telephone_book.search(number)
total_comparisons += comparisons
print("Total number of comparisons for the set of telephone numbers:",
total_comparisons)
elif choice == '4':
print("Exiting...")
break
else:
print("Invalid choice. Please try again.")
if __name__ == '__main__':
main()