Find the closet points

Consider you are given n data points in the form of list of tuples like S=[(x1,y1),(x2,y2),(x3,y3),(x4,y4),(x5,y5),…,(xn,yn)] and a point P=(p,q)
your task is to find 5 closest points(based on cosine distance) in S from P

Cosine distance between two points (x,y) and (p,q) is defined as cos−1((x⋅p+y⋅q)(√x2+y2)⋅(√p2+q2))cos−1((x⋅p+y⋅q)(x2+y2)⋅(p2+q2))

Ex:

S= [(1,2),(3,4),(-1,1),(6,-7),(0, 6),(-5,-8),(-1,-1)(6,0),(1,-1)]
P= (3,-4)


Output:
(6,-7)
(1,-1)
(6,0)
(-5,-8)
(-1,-1)
Here is my implementation

import math

S = [(1, 2), (3, 4), (-1, 1), (6, -7), (0, 6), (-5, -8), (-1, -1), (6, 0), (1, -1)]
P = (3,-4)
S.sort(key=lambda x: math.sqrt((float(x[0]) - 3) ** 2 +
(float(x[1]) - (-4)) ** 2))
print(S)
But I am getting output as
[(1, -1), (6, -7), (-1, -1), (6, 0), (1, 2)]
Please help me

Maybe you should use the search function before posting, since someone else has already asked your homework problem: https://www.sitepoint.com/community/t/find-the-closest-m-points-from-a-given-point-p

Also you should probably figure out the difference between python and perl.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.