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日

悬赏问题

  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 wpf界面一直接收PLC给过来的信号,导致UI界面操作起来会卡顿
  • ¥15 init i2c:2 freq:100000[MAIXPY]: find ov2640[MAIXPY]: find ov sensor是main文件哪里有问题吗
  • ¥15 运动想象脑电信号数据集.vhdr
  • ¥15 三因素重复测量数据R语句编写,不存在交互作用
  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了