Reputation: 3
I am trying to complete this question. I don't know where I'm going wrong..
First line of the input is a number, which indicates how many pairs of words will follow (each pair in a separate line). The pairs are of the form COUNTRY CITY specifying in which country a city is located. The last line is the name of a city. Print the number of cities that are located in the same country as this city.
Hint. Use dictionaries.
For example, on input:
6
UK London
US Boston
UK Manchester
UK Leeds
US Dallas
Russia Moscow
Manchester
output must be: 3
from collections import defaultdict
n=input()
d=defaultdict(list)
city=' '
for i in range(0,int(n)):
kv=input().split()
d[kv[0]].append(kv[1])
for k1,v1 in d.items():
if v1==city:
print(len(k1))
Upvotes: 0
Views: 776
Reputation: 21285
Like others mentioned, you need to take input for the query city as well. And additionally you can approach this a bit differently - you don't need defaultdict
. Since your query is a city, let's store that as the key in the dictionary, with the value being the country. Then we can find which country we need to get. After than it's just a matter of counting up the values of that country in the dictionary.
n = input()
city_to_country = {}
for i in range(0, int(n)):
kv = input().split()
city_to_country[kv[1].rstrip()] = kv[0]
query_city = input()
target_country = city_to_country[query_city]
print(list(city_to_country.values()).count(target_country))
Upvotes: 0
Reputation: 2806
You missing the input of the city And you need to check if the city is in the list, and just then count how many there are
from collections import defaultdict
n=input()
d=defaultdict(list)
city=' '
for i in range(0,int(n)):
kv=input().split()
d[kv[0]].append(kv[1])
city = input('Enter a city')
for k1,v1 in d.items():
if city in v1:
print(len(v1))
Upvotes: 1