Find a closest point to another set [closed]
I am trying to create a function to determine which of a set of points (represented as a list of coordinates lists) is closest to another given point. It should return the index in the list where that point appears:
Here is the code I've written so far:
def sq_dist(p1: tuple[int, int], p2: tuple[int, int]) -> int:
"""Square of Euclidean distance between p1 and p2
>>> sq_dist([2, 3], [3, 5])
5
"""
x1, y1 = p1
x2, y2 = p2
dx = x2 - x1
dy = y2 - y1
return dx*dx + dy*dy
def closest_index(point: tuple[int, int], centroids: list[tuple[int, int]]) -> int:
count = 0
soopa_distance = 1000000000000000000000000000000000000000000000000
for p in centroids:
distance = sq_dist(point,p)
if distance < soopa_distance:
soopa_distance = distance
else:
count = count +1
return count
Unfortunately it doesn't return the expected index:
point_set1 = [[4,5],[3,4],[2,3],[1,2],[1,1]]
print(closest_index([0,0], point_set1))
# 0
point_set2 = [[1,2],[2,3],[3,4],[4,5],[1,1]]
print(closest_index([0,0], point_set2))
# 3
# Expected result in both cases: 4
Can you please help me identify and fix the error(s) ?
Comments
Post a Comment