Skip to content

Commit aa3f455

Browse files
closestpairofpoints.py
1 parent 7df63d9 commit aa3f455

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed
+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
from math import sqrt, pow
2+
3+
def distance(a, b):
4+
return sqrt(pow(a[0] - b[0],2) + pow(a[1] - b[1],2))
5+
6+
def bruteMin(points, current=float("inf")):
7+
if len(points) < 2: return current
8+
else:
9+
head = points[0]
10+
del points[0]
11+
newMin = min([distance(head, x) for x in points])
12+
newCurrent = min([newMin, current])
13+
return bruteMin(points, newCurrent)
14+
15+
def divideMin(points):
16+
points = sorted(points)
17+
half = len(sorted(points))/2
18+
minimum = min([bruteMin(points[:half]), bruteMin(points[half:])])
19+
nearLine = filter(lambda x: x[0] > half - minimum and x[0] < half + minimum, points)
20+
return min([bruteMin(nearLine), minimum])
21+
22+
list1 = [(12,30), (40, 50), (5, 1), (12, 10), (3,4)]
23+
list2=[(1, 496.5), (12,30), (40, 50), (5, 1), (12, 10), (3,4), (1, 496), (1, 497)]
24+
print "Closest Pair Distance:",divideMin(list1)
25+
print "Closest Pair Distance:",divideMin(list2)

0 commit comments

Comments
 (0)