Error found while executing my code at practise problems 1012-9


While I submitted my answer at the Python Fundamentals Practice Problems on 1012-9 I’ve got this answer: "Your function returned an incorrect answer. Input: [10, 10] Your answer: COACH HOUSE INN Expected answer: MCDONALD'S HAMBURGERS "

My code for this screen was:

provided input

x = 100
y = 100

answer to this input: LEADBETTERS II

from csv import reader
import math
def distance(x_1, y_1, x_2, y_2):
return math.sqrt((x_1 - x_2)**2 + (y_1 - y_2)**2)

def closest_restaurant(x,y):
with open(‘restaurants.csv’) as f:
f_csv = reader(f)
for row in restaurant:
return min(distance_rest,key=distance_rest.get)


At the x=100,y=100 coordinates it provided the right answer (‘LEADBETTERS II’)

Can you please direct me where did I have gone wrong in this situation?

Thank you in advance

I believe the error is when you try to get the min from the dictionary. The thing is you need to get the min value, not the min key from te dictionary. Then you need to find the key for that value.

This is how I’d do:

minimum = min(dict.values())

for key in dict.keys():
    if dict[key] == minimum:
         return key

Hope it helps.

Hello Otavios

I have tried your solution but the result is the same as when I tried my code.

Any suggestion from the Dataquest team?


Well, that’s odd.

However, I do not think the dictionary approach is best one to this problem as dictionaries are hard to sort.

What I did when I solved this was to create to variables, the first on to retain the closest distance and the second one to retain the name of the closest restaurant. Then, inside the loop I wrote an if to check if the restaurant in the current loop is closest than the current closest restaurants and, if it is, the variables I created have new values assign to them.

I don’t know if I was clear enough, so this is the code:

closest_name = None
min_distance = None

for restaurant in restaurants:
    restaurant_name = restaurant[0]
    dist = distance(x, y, int(restaurant[3]), int(restaurant[4]))
    if min_distance is None or dist < min_distance:
        min_distance = dist
        closest_name = restaurant_name 
return closest_name