Python是一種高級編程語言,廣泛應用于各種領域。其中算法也是Python的一大優勢,今天我們來探討一下Python中一個著名算法——最接近點對。
def distance(a, b): return ((a[0] - b[0])**2 + (a[1] - b[1])**2) ** 0.5 def closest_pair(points): n = len(points) if n<= 1: return None, None elif n == 2: return points[0], points[1] px = sorted(points, key=lambda x: x[0]) py = sorted(points, key=lambda y: y[1]) left_x = px[:n//2] right_x = px[n//2:] mid_x = left_x[-1][0] left_y = [] right_y = [] for point in py: if point in left_x: left_y.append(point) else: right_y.append(point) (p1, q1) = closest_pair(left_x) (p2, q2) = closest_pair(right_x) if p1 is None or q1 is None: min_dist = distance(p2, q2) pair = (p2, q2) elif p2 is None or q2 is None: min_dist = distance(p1, q1) pair = (p1, q1) else: d1 = distance(p1, q1) d2 = distance(p2, q2) if d1<= d2: min_dist = d1 pair = (p1, q1) else: min_dist = d2 pair = (p2, q2) (p3, q3) = closest_split_pair(py, mid_x, min_dist, pair) if p3 is None or q3 is None: return pair else: d3 = distance(p3, q3) if d3<= min_dist: return p3, q3 else: return pair def closest_split_pair(py, mid_x, min_dist, pair): sy = [x for x in py if mid_x - min_dist<= x[0]<= mid_x + min_dist] best_pair = pair n = len(sy) for i in range(n): for j in range(i+1, min(i+7, n)): p, q = sy[i], sy[j] d = distance(p, q) if d< min_dist: min_dist = d best_pair = p, q return best_pair
這就是Python實現最接近點對的程序,我們可以看到這段程序通過遞歸的方式實現了找到最接近點對的過程。具體實現就是不斷地對點集遞歸地分成左右兩個子集,最后將左右子集的結果歸并為最終結果,其中還考慮到了特判等問題。這種算法能夠在$O(n log n)$的時間內解決這個問題,操作簡單高效。
上一篇python 最小系統
下一篇vue data 追加