Computer Science

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.

Python Searching

2 Likes

Answer

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

keys = [None, None, None, None, None, None, None, None, None, None, None]  
values = [None, None, None, None, None, None, None, None, None, None, None]

def calculate_hash_index(key):
    return len(key) - 1

for country, capital in CountryCapital.items():
    index = calculate_hash_index(country)
    keys[index] = country
    values[index] = capital

print("hash index = length of key - 1 | List of Keys | List of Values")

for i in range(len(keys)):
    print(str(i) + "| " + str(keys[i]) + "| " + str(values[i]))
search_keys = ['India', 'France', 'USA']
print("\nSearch Results:")
for key in search_keys:
    index = calculate_hash_index(key)
    if keys[index] == key:
        print("Capital of", key, ":", values[index])
    else:
        print("Capital of ", key, ": Not found")
Output
hash index = length of key - 1 | List of Keys | List of Values
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

Search Results:
Capital of India : New Delhi
Capital of France : Paris
Capital of  USA : Not found

Answered By

1 Like


Related Questions