The Tree, One Merge at a Time

Classic MLMedium+20 XP+20

The Tree, One Merge at a Time

Hierarchical clustering starts with every point as a cluster of its own and repeats one move: merge the two closest clusters. It stops when a single cluster is left. The list of merges it makes, with the distance at which each one happened, is exactly what a dendrogram draws: every merge is a branch point, and its distance is that branch's height.

Task: write merge_history(points, linkage), where points is a list of (x, y) pairs (point i is the i-th pair) and linkage is "single", "complete" or "average". Return the list of merges in the order they happen.

The distance between two points is straight-line (Euclidean) distance. The distance between two clusters depends on linkage, and is always worked out from the original points:

linkagedistance between clusters AAA and BBB
"single"the distance of the closest pair, one point from AAA and one from BBB
"complete"the distance of the farthest pair, one point from AAA and one from BBB
"average"the average distance over every pair with one point from AAA and one from BBB

Each merge is a tuple (left, right, height):

  • left and right are the two clusters being joined, each a sorted list of point indices, and left is the one holding the smaller index;
  • height is the linkage distance between them at the moment they merge, rounded to 4 decimal places.

A list of nnn points makes n−1n - 1n−1 merges, so a single point makes none. The tests never have two pairs of clusters tied for closest.

Different Ways to Measure "Closest"

Once a cluster has more than one point, "closest" needs a rule. Try each one below.

Single distance: 197

Single linkage looks only at the two nearest points, one from each cluster. Even one close pair is enough to pull clusters together.

Examples

points = [(0, 0), (1, 0), (5, 0), (6.5, 0), (15, 0)]
linkage = "single"
returns [([0], [1], 1.0), ([2], [3], 1.5), ([0, 1], [2, 3], 4.0), ([0, 1, 2, 3], [4], 8.5)]
points = [(0, 0), (1, 0), (5, 0), (6.5, 0), (15, 0)]
linkage = "complete"
returns [([0], [1], 1.0), ([2], [3], 1.5), ([0, 1], [2, 3], 6.5), ([0, 1, 2, 3], [4], 15.0)]

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run