Editor

Nearest Neighbor Route

Advanced · Write the code · from Algorithmic Efficiency and Heuristics: Reasonable and Unreasonable Time

From the lesson: Algorithmic Efficiency and Heuristics: Reasonable and Unreasonable Time

Efficiency is how much computing work an algorithm needs, and it decides whether a program answers in the blink of an eye or would need longer than the age of the universe. Two correct algorithms for the same job can sit at opposite ends of that range.

Read the lesson

Write nearest_neighbor_route(stops). stops is a dictionary from a place name to its (x, y) position, and the first key is the starting point. Build a route with the nearest-neighbor heuristic: from the current place, go to the closest place not visited yet, until every place is visited, then return to the start.

Return the route as a list of names, starting and ending with the first key. If two places are equally close, choose the one that comes first in the dictionary. Use math.dist(a, b) for the distance between two positions.

nearest_neighbor_route({"A": (0, 0), "B": (5, 0), "C": (1, 0)})
->  ['A', 'C', 'B', 'A']
import math
def nearest_neighbor_route(stops):
# Start at the first key, keep going to the closest unvisited place
pass

What Check runs

Your code runs first, then each of these lines, and 2 more that stay hidden. The output must match exactly.

RunsExpected output
nearest_neighbor_route({"A": (0, 0), "B": (5, 0), "C": (1, 0)})['A', 'C', 'B', 'A']
nearest_neighbor_route({"Home": (0, 0), "Shop": (0, 3), "Gym": (4, 3), "Cafe": (4, 0)})['Home', 'Shop', 'Gym', 'Cafe', 'Home']

More Algorithmic Efficiency exercises

All Python exercises · 50 practice problems