Skip to content

Instantly share code, notes, and snippets.

@cunla
Created June 5, 2020 18:23
Show Gist options
  • Save cunla/5f744aa4652b22218b313f2c14dcfe07 to your computer and use it in GitHub Desktop.
Save cunla/5f744aa4652b22218b313f2c14dcfe07 to your computer and use it in GitHub Desktop.
Find k closest points in python
import heapq
def k_closest_points(points_list, point, k):
# Find k closest points to point in points_list
points_distance = []
for p in points_list:
distance = (p[0] - point[0]) ** 2 + (p[1] - point[1]) ** 2
points_distance.append((distance, p))
heapq.heapify(points_distance)
res = []
for i in range(k):
p = heapq.heappop(points_distance)
res.append(p[1])
return res
if __name__ == '__main__':
assert k_closest_points([(1, 1), (2, 2), (3, 3), (4, 4), (0.5, 0.5)], (0, 0), 2) == [(0.5, 0.5), (1, 1)]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment