Python_yangyi 2023-01-11 22:54 采纳率: 50%
浏览 26
已结题

在K-D Tree中对于“the nearest neighbor query”的定义出现问题

在对K-D Tree 类的编写的时候定义the nearest neighbor query时发生错误

img

问题显示“缩进”出现问题

尝试调整缩进但似乎出现了更多的问题

def nearest_neighbor(self, point: Point) -> Point:
        closest = None
        depth = 0
        return self._nearest_neighbor(point, self._root, closest, depth)

    def _nearest_neighbor(self, point, node, closest, depth):
       if node is None:
            return closest
       if closest is None or self.distance(point, node.location) < self.distance(point, closest):
           closest = node.location
        axis = depth % 2
        if point[axis] < node.location[axis]:
           closest = self._nearest_neighbor(point, node.left, closest, depth+1)
        else:
            closest = self._nearest_neighbor(point, node.right, closest, depth+1)
        return closest

    def distance(self, p1, p2):
        return ((p1.x - p2.x) ** 2 + (p1.y - p2.y) ** 2) ** 0.5

def range_test():
    points = [Point(7, 2), Point(5, 4), Point(9, 6), Point(4, 7), Point(8, 1), Point(2, 3)]
    kd = KDTree()
    kd.insert(points)
    result = kd.range(Rectangle(Point(0, 0), Point(6, 6)))
    assert sorted(result) == sorted([Point(2, 3), Point(5, 4)])

  • 写回答

3条回答 默认 最新

  • 谛凌 2023-01-11 23:06
    关注

    你的代码是有从网页复制的吗?可能是tab和空格混用导致缩进出现了问题
    试试这个

    
    def nearest_neighbor(self, point: Point) -> Point:
        closest = None
        depth = 0
        return self._nearest_neighbor(point, self._root, closest, depth)
     
    def _nearest_neighbor(self, point, node, closest, depth):
        if node is None:
            return closest
        if closest is None or self.distance(point, node.location) < self.distance(point, closest):
            closest = node.location
        axis = depth % 2
        if point[axis] < node.location[axis]:
            closest = self._nearest_neighbor(point, node.left, closest, depth+1)
        else:
            closest = self._nearest_neighbor(point, node.right, closest, depth+1)
        return closest
    
    def distance(self, p1, p2):
        return ((p1.x - p2.x) ** 2 + (p1.y - p2.y) ** 2) ** 0.5
     
    def range_test():
        points = [Point(7, 2), Point(5, 4), Point(9, 6), Point(4, 7), Point(8, 1), Point(2, 3)]
        kd = KDTree()
        kd.insert(points)
        result = kd.range(Rectangle(Point(0, 0), Point(6, 6)))
        assert sorted(result) == sorted([Point(2, 3), Point(5, 4)])
     
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录
查看更多回答(2条)

报告相同问题?

问题事件

  • 系统已结题 1月20日
  • 已采纳回答 1月12日
  • 创建了问题 1月11日

悬赏问题

  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来