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) :
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
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started