MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / search

Function search

data_structures/kd_tree/nearest_neighbour_search.py:34–76  ·  view source on GitHub ↗

Recursively searches for the nearest neighbor in the KD-Tree. Args: node: The current node in the KD-Tree. depth: The current depth in the KD-Tree.

(node: KDNode | None, depth: int = 0)

Source from the content-addressed store, hash-verified

32 nodes_visited: int = 0
33
34 def search(node: KDNode | None, depth: int = 0) -> None:
35 """
36 Recursively searches for the nearest neighbor in the KD-Tree.
37
38 Args:
39 node: The current node in the KD-Tree.
40 depth: The current depth in the KD-Tree.
41 """
42 nonlocal nearest_point, nearest_dist, nodes_visited
43 if node is None:
44 return
45
46 nodes_visited += 1
47
48 # Calculate the current distance (squared distance)
49 current_point = node.point
50 current_dist = sum(
51 (query_coord - point_coord) ** 2
52 for query_coord, point_coord in zip(query_point, current_point)
53 )
54
55 # Update nearest point if the current node is closer
56 if nearest_point is None or current_dist < nearest_dist:
57 nearest_point = current_point
58 nearest_dist = current_dist
59
60 # Determine which subtree to search first (based on axis and query point)
61 k = len(query_point) # Dimensionality of points
62 axis = depth % k
63
64 if query_point[axis] <= current_point[axis]:
65 nearer_subtree = node.left
66 further_subtree = node.right
67 else:
68 nearer_subtree = node.right
69 further_subtree = node.left
70
71 # Search the nearer subtree first
72 search(nearer_subtree, depth + 1)
73
74 # If the further subtree has a closer point
75 if (query_point[axis] - current_point[axis]) ** 2 < nearest_dist:
76 search(further_subtree, depth + 1)
77
78 search(root, 0)
79 return nearest_point, nearest_dist, nodes_visited

Callers 1

nearest_neighbour_searchFunction · 0.70

Calls

no outgoing calls

Tested by

no test coverage detected