-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkclosest.py
33 lines (32 loc) · 876 Bytes
/
kclosest.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import math
def sortPoints(InputList):
# Selection Sort
for i in range(1, len(InputList)):
j = i-1
nxt_element = InputList[i]
# Compare the current element with next one
while (InputList[j] > nxt_element) and (j >= 0):
InputList[j+1] = InputList[j]
j=j-1
InputList[j+1] = nxt_element
return InputList
def kNearest(points, input,k=3):
[m,n] = input
result=[]
tem=[]
variable={}
for i in points:
[p,q] = i
sqrt=math.sqrt(((m-p)*(m-p))+((n-q)*(n-q)))
tem.append(sqrt)
variable[sqrt]=i
sortPoints(tem)
for j in tem:
if len(result)>k-1:
break
result.append(variable[j])
return result
input = [0,0]
post_offices = [[-16,5],[-1,2],[4,3],[10,-2],[0,3],[-5,-9]]
result= kNearest(post_offices,input)
print (result)