Skip to content
Exercises · Q9
Q.

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. So that we end up with:

hash index = length of key - 1List of KeysList of Values
0NoneNone
1UKLondon
2NoneNone
3CubaHavana
4IndiaNew Delhi
5FranceParis
6NoneNone
7NoneNone
8AustraliaCanberra
9NoneNone
10SwitzerlandBerne

Now search the capital of India, France and the USA in the hash table and display your result.

Sikkim CbseNCERTSubjective· 3mImportance★★★★★
94% · 16/17 Questions
🔒 Locked · start free trial →

You're viewing a preview — the full solution, concept, methods & PYQ mapping are locked.

Start your 14-day free trial to unlock the full solution →

This question implements a custom hash table where the hash function is the length of the country name. We store keys and values in parallel lists at index = len(key) - 1, then search by computing the same hash and checking for a match.

This is a code task — you need to write a Python program that builds this specific hash table and then searches for given countries.

The core idea here is direct addressing using a hash function. Instead of a traditional hash table with collision handling, this problem uses a very simple hash: the length of the key string. The "hash table" is just two parallel lists (one for keys, one for values) sized to accommodate the longest country name. The index where a key-value pair is stored is len(country) - 1 (because lists are 0-indexed).

Why this approach? It's a teaching example to show that a hash function maps a key to an index. The simplicity lets you focus on the concept: compute the hash, store at that index, and to search, compute the same hash and check if the key at that index matches.

Watch out

This hash function is not collision-resistant — two countries of the same length would overwrite each other. The problem avoids this by giving countries of unique lengths. In real hash tables, you'd handle collisions with chaining or open addressing.

Here's the complete, runnable Python program:

# Given mapping
CountryCapital = {
    'India': 'New Delhi',
    'UK': 'London',
    'France': 'Paris',
    'Switzerland': 'Berne',
    'Australia': 'Canberra'
}

# Find the maximum hash index needed
# Hash = len(country) - 1, so max index = max(len(country)) - 1
max_len = max(len(country) for country in CountryCapital.keys())
table_size = max_len  # indices 0 to max_len-1

# Initialize two lists with None
keys_list = [None] * table_size
values_list = [None] * table_size

# Populate the hash table
for country, capital in CountryCapital.items():
    hash_index = len(country) - 1  # hash function: length of country name
    keys_list[hash_index] = country
    values_list[hash_index] = capital

# Display the table (optional, for verification)
print("Hash Table (index | key | value):")
for i in range(table_size):
    print(f"{i:2d} | {keys_list[i]:15s} | {values_list[i]}")

print("\n" + "="*50)

# Search function
def search_capital(country_name):
    hash_index = len(country_name) - 1
    
    # Check if index is within bounds
    if hash_index >= table_size or hash_index < 0:
        return f"{country_name} not found (hash index out of range)"
    
    # Check if the key at that index matches
    if keys_list[hash_index] == country_name:
        return f"Capital of {country_name} is {values_list[hash_index]}"
    else:
        return f"{country_name} not found in hash table"

# Search for the required countries
countries_to_search = ['India', 'France', 'USA']
for country in countries_to_search:
    print(search_capital(country))

Expected output:

Hash Table (index | key | value):
 0 | None            | None
 1 | UK              | London
 2 | None            | None
 3 | None            | None
 4 | India           | New Delhi
 5 | France          | Paris
 6 | None            | None
 7 | None            | None
 8 | Australia       | Canberra
 9 | None            | None
10 | Switzerland     | Berne

==================================================
Capital of India is New Delhi …

Unlock everything free for 14 days

  • Full step-by-step solutions
  • Concept-first explanations
  • Methods, shortcuts & mistakes
  • PYQ mapping + timed mock tests

Full access for 14 days. No credit card required.