def pre(points): '''Pre-process for closest pair problem, 'points' being a list of 2-tuples. return two ordered list based on x and y coordinates using merge sort.''' px = merge_sort_2d(points, 0) py = merge_sort_2d(points, 1) return px, py
def closest_pair(Px, Py): '''Divide the points into 2 halves, left and right, for each sorted copies of the original data, find the closest pair in each half, compare with the possible closest pairs, of which each point in different halves, return the minimum.''' mid = int(len(Px)/2) left_x = Px[:mid] right_x = Px[mid:] left_y = Py[:mid] right_y = Py[mid:] pair_dist = [] #base case if len(Px) == 1: return None elif len(Px) == 2: return Px else: left = closest_pair(left_x, left_y) #left is a list of two points right = closest_pair(right_x, right_y) #if None is in (left, right), it has to be left if left == None: delta = dist(right) else: delta = min(dist(left), dist(right)) split = closest_split_pair(Px, Py, delta) pair_dist = [(x, dist(x)) for x in (left, right, split) if x] return merge_sort_2d(pair_dist, 1)[0][0]