Skip to content

Commit 8b238d1

Browse files
docstring for search()
1 parent 81d6917 commit 8b238d1

File tree

1 file changed

+20
-3
lines changed

1 file changed

+20
-3
lines changed

data_structures/kd_tree/nearest_neighbour_search.py

+20-3
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,10 @@
11
from typing import Optional, List, Tuple
22
from .kd_node import KDNode
33

4-
def nearest_neighbour_search(root: Optional[KDNode], query_point: List[float]) -> Tuple[Optional[List[float]], float, int]:
4+
def nearest_neighbour_search(
5+
root: Optional[KDNode],
6+
query_point: List[float]
7+
) -> Tuple[Optional[List[float]], float, int]:
58
"""
69
Performs a nearest neighbor search in a KD-Tree for a given query point.
710
@@ -20,6 +23,18 @@ def nearest_neighbour_search(root: Optional[KDNode], query_point: List[float]) -
2023
nodes_visited: int = 0
2124

2225
def search(node: Optional[KDNode], depth: int = 0) -> None:
26+
"""
27+
Recursively searches the KD-Tree to find the nearest point to the query point.
28+
29+
Args:
30+
node (Optional[KDNode]): The current node being examined.
31+
depth (int): The current depth of the tree, which determines the axis to split on.
32+
33+
Updates:
34+
nearest_point: The closest point found so far in the KD-Tree.
35+
nearest_dist: The squared distance from the query point to the nearest point found.
36+
nodes_visited: The number of nodes visited during the search.
37+
"""
2338
nonlocal nearest_point, nearest_dist, nodes_visited
2439
if node is None:
2540
return
@@ -28,7 +43,9 @@ def search(node: Optional[KDNode], depth: int = 0) -> None:
2843

2944
# Calculate the current distance (squared distance)
3045
current_point = node.point
31-
current_dist = sum((query_coord - point_coord) ** 2 for query_coord, point_coord in zip(query_point, current_point))
46+
current_dist = sum(
47+
(query_coord - point_coord) ** 2 for query_coord, point_coord in zip(query_point, current_point)
48+
)
3249

3350
# Update nearest point if the current node is closer
3451
if nearest_point is None or current_dist < nearest_dist:
@@ -49,7 +66,7 @@ def search(node: Optional[KDNode], depth: int = 0) -> None:
4966
# Search the nearer subtree first
5067
search(nearer_subtree, depth + 1)
5168

52-
# If the further subtree has a closer point
69+
# If the further subtree has a closer point, search it
5370
if (query_point[axis] - current_point[axis]) ** 2 < nearest_dist:
5471
search(further_subtree, depth + 1)
5572

0 commit comments

Comments
 (0)