I'm trying to code something similar to k-nearest neighbors, but way simpler for my algorithms and data structure class.
This is what is asked:
Calculate the k-nearest neighbors of a given point q in A. Note that k is a natural number >= 1, q is an integer that represents the index of the point in A that contains q, and A is an array of 2D points.
This method must return an ordered list of k neighbors, where the order is determined by the indices of the neighbors in A. If there are fewer than k neighbors in A, the list should be empty.
This is my code:
import math
def euclidean_distance(A, q):
return math.sqrt((A[q][0] - A[0][0])**2 + (A[q][1] - A[0][1])**2)
def knn(k, q, A):
distances = []
for i in range(len(A)):
distances.append((euclidean_distance(A, i), i))
distances.sort(key=lambda x: x[0])
return distances[:k]
However, it doesn't pass any tests and I don't know why. Here are the tests:
A = [[0.0,0.0], [1.0,1.0], [4.0,1.0], [0.0,3.0], [1.0,3.0]]
assert kkn(2,0,A) == [1,3]
assert kkn(2,1,A) == [0,4]
assert kkn(2,2,A) == [1,4]
assert kkn(2,3,A) == [1,4]
assert kkn(2,4,A) == [1,3]