Question: Write a function called closest() that accepts a single parameter labelled_points, which is a dictionary of labelled points on a Cartesian plane. The function should
Write a function called closest() that accepts a single parameter labelled_points, which is a dictionary of labelled points on a Cartesian plane. The function should return a list of tuples that contain the label of the closest point (not including itself) for each point in the dictionary.
A set of points are stored in a dictionary where the label for the point is used as the key, and a tuple representing the location on a Cartesian plane is the value associated with each key.
For example:
{'A': (2.5, 0.5), 'B': (1, 2), 'C': (1, 1), 'D': (0, 2)} The distance between two points A and B can be calculated with the equation:
For each point, identify the closest point (not including itself) and produce a tuple containing labels of the point and its closest point). In the figure above, the closest point to A is C, so the tuple ('A', 'C') is used to record the closest point to A. If two points are equally distant then select the one with the label that is ordered first alphabetically (according to standard character ordering). The list containing pairs of labels should be ordered according to the first element of the pair.
For example, given the set of points shown above:
{'A': (2.5, 0.5), 'B': (1, 2), 'C': (1, 1), 'D': (0, 2)} The list returned from the function should be:
[('A', 'C'), ('B', 'C'), ('C', 'B'), ('D', 'B')] Notes:
Your code should still work when a single point is given. In that case the closest point will be empty.
You can assume the source dictionary of points will contain at least one point.
For example:
| Test | Result |
|---|---|
points = {'A': (2.5, 0.5), 'B': (1, 2), 'C': (1, 1)} result = closest(points) print(result) | [('A', 'C'), ('B', 'C'), ('C', 'B')] |
points = {'A': (-1, -1), 'B': (1, 1), 'C': (3, 3), 'D': (4, 4)} result = closest(points) print(result) | [('A', 'B'), ('B', 'A'), ('C', 'D'), ('D', 'C')] |
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
