您可以将这些项目视为高维空间中的点,并将它们全部插入到 BSP 树中,例如kd 树。要使用属性权重,您只需将它们乘以相应的坐标:(w1*x, w2*y, ...)
准备:(来自维基百科,python代码)
def kdtree(point_list, depth=0):
if not point_list:
return None
# Select axis based on depth so that axis cycles through all valid values
k = len(point_list[0]) # assumes all points have the same dimension
axis = depth % k
# Sort point list and choose median as pivot element
point_list.sort(key=lambda point: point[axis])
median = len(point_list) // 2 # choose median
# Create node and construct subtrees
node = Node()
node.location = point_list[median]
node.left_child = kdtree(point_list[:median], depth + 1)
node.right_child = kdtree(point_list[median + 1:], depth + 1)
return node
搜索:(来自gist,基于维基百科算法)
# method of the Node-class
def closest_point(self, target, point, best=None):
if target is None:
return best
if best is None:
best = target
# consider the current node
if distance(target, point) < distance(best, point):
best = target
# search the near branch
best = self.child_near(point).closest_point(point, best)
# search the away branch - maybe
if self.distance_axis(point) < distance(best, point):
best = self.child_away(point).closest_point(target, point, best)
return best
阅读更多: