Write a Python program by considering a mapping of list of countries and their capital cities such as: CountryCapital = { 'India' : 'New Delhi', 'UK' : 'London', 'France' : 'Paris', 'Switzerland' : 'Berne', 'Australia' : 'Canberra' }. Let us presume that our hash function is the length of the Country Name. Take two lists of appropriate size: one for keys (Country) and one for values (Capital). To put an element in the hash table, compute its hash code by counting the number of characters in Country, then put the key and value in both the lists at the corresponding indices. For example, India has a hash code of 5. So, we store India at the 5th position (index 4) in the keys list, and New Delhi at the 5th position (index 4) in the values list and so on. Now search the capital of India, France and the USA in the hash table and display your result.
Program to implement hash table for Country-Capital mapping
Define the dictionary
CountryCapital = {'India': 'New Delhi', 'UK': 'London', 'France': 'Paris', 'Switzerland': 'Berne', 'Australia': 'Canberra'}
Create two lists for hash table (size 11 for indices 0-10)
keys = [None] * 11 values = [None] * 11
Insert elements into hash table using hash function: length of country name - 1
for country, capital in CountryCapital.items(): hash_index = len(country) - 1 keys[hash_index] = country values[hash_index] = capital
Function to search capital in hash table
def search_capital(country): hash_index = len(country) - 1 if hash_index < len(keys) and keys[hash_index] == country: return values[hash_index] return None
Search for India, France and USA
print("Search Results:") for country in ['India', 'France', 'USA']: capital = search_capital(country) if capital: print(f"Capital of {country} is {capital}") else: print(f"{country} not found in hash table")
Output:
Capital of India is New Delhi
Capital of France is Paris
USA not found in hash table
Explanation
The program implements a hash table using two parallel lists. The hash function calculates the index as (length of country name - 1). For insertion, each country-capital pair is stored at the computed index. India (length 5) goes to index 4, France (length 6) to index 5, UK (length 2) to index 1, Australia (length 9) to index 8, and Switzerland (length 11) to index 10. During search, the same hash function computes the index and checks if the key matches. India and France are found at their respective indices, while USA (length 3, index 2) is not found as no country exists at that position.
Solution Steps
Step 1: Create two lists 'keys' and 'values' of size 11 initialized with None.
Step 2: For each country-capital pair, compute hash_index = len(country) - 1.
Step 3: Store country in keys[hash_index] and capital in values[hash_index].
Step 4: For searching, compute hash_index using same formula and check if keys[hash_index] matches the search country.
Step 5: If match found, return corresponding value; else return None.