You are working with points in an n-dimensional Euclidean space, where each point is represented as a list (or array) of numeric coordinates.
Assume:
list[float]
.
1 <= k <= len(dataset)
.
Write a function that computes the Euclidean distance between two points in n-dimensional space.
The function should:
p: list[float]
and
q: list[float]
.
float
.
The Euclidean distance between points p and q in n dimensions is:
Examples:
[1, 2]
and
[4, 6]
in 2D space.
[1, 2, 3]
and
[4, 5, 6]
in 3D space.
You do not need to print anything; just implement the function that returns the distance.
Using the Euclidean distance function from part (1) as the distance metric, write a function to find the k-nearest neighbors of a query point within a dataset.
The function should:
query_vector: list[float]
— the query point.
k: int
— the number of nearest neighbors to return.
dataset: list[list[float]]
— a list of data points, where each data point is a list of floats of the same dimension as
query_vector
.
query_vector
to each point in
dataset
.
list[int]
of the indices of the
k nearest neighbors
in
dataset
,
sorted in order of increasing distance
to the query.
Example dataset:
dataset = [
[10, 11, 12], # index 0
[1, 2, 3], # index 1
[4, 5, 6], # index 2
[7, 8, 9], # index 3
[13, 14, 15] # index 4
]
Given some query_vector and a value of k, your function should return the indices of the k closest points from this dataset, ordered from closest to farthest.