Question: Python computing Write a function kclosest(place, k, locations) that returns a list of the k closest locations to a given place, ordered by increasing distance.

Python computing

Write a function kclosest(place, k, locations) that returns a list of the k closest locations to a given place, ordered by increasing distance.

If there are multiple locations at equal distance to the given place, you need to choose between them, return the ones that appear first in the list of the locations

Assumptions

You can assume that k > 0.

You can assume that the locations contain at least kdistinct places (with no duplicate places). For example, [("place1",4.1, 2), ("place2", 4.1, 2), ("place3", 2, 2)] is a valid list of locations (where "place1" and "place2" happen to be at the same coordinates). In contrast, [("place1", 4.1,2), ("place1", 4.1, 2), ("place3", 2, 2)] is not a valid list of locations, as "place1" appears twice.

You should calculate the distance between an observation and the test point using the Euclidean distance between two points(x1,y1)and(x2,y2) :

Python computing Write a function kclosest(place, k, locations) that returns a list

Example calls to the function are:

>>> print(kclosest((4,1), 1, [("ngv", 4, 0), ("town hall", 4, 4), ("myhotel", 2, 2), ("parliament", 8, 5.5), ("fed square", 4, 2)])) 
["ngv"] 
>>> print(kclosest((4,1), 2, [("ngv", 4, 0), ("town hall", 4, 4), ("myhotel", 2, 2), ("parliament", 8, 5.5), ("fed square", 4, 2)])) 
["ngv", "fed square"] 
>>> print(kclosest ((2,2), 3, [("ngv", 4, 0), ("town hall", 4, 4), ("myhotel", 2, 2), ("parliament", 8, 5.5), ("fed square", 4, 2)])) 
["myhotel","fed square","ngv"] 
>>> print(kclosest ((2,2), 4, [("ngv", 4, 0), ("town hall", 4, 4), ("myhotel", 2, 2), ("parliament", 8, 5.5), ("fed square", 4, 2)])) 
["myhotel","fed square","ngv","town hall"] 

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!