python – 从树递归中返回值列表

我正在尝试自学数据结构,我正在用
Python实现一个k-d树.我有一种方法在我的k-d树类中的一个点的某个半径内搜索树中的点:

def within_radius(self, point, radius, result=[]):
    """
    Find all items in the tree within radius of point
    """
    d = self.discriminator

    if in_circle(point, radius, self.data):
        result.append(self.data)

    # Check whether any of the points in the subtrees could be
    # within the circle
    if point[d] - radius < self.data[d] and self.l_child:
        result.append(self.l_child.within_radius(point, radius, result))

    if point[d] + radius > self.data[d] and self.r_child:
        result.append(self.r_child.within_radius(point, radius, result))

    return result

它可以工作,但它返回的列表非常时髦,带有结果的递归调用的重复值.将从树递归返回的值“累积”到列表中的好方法是什么?我已经考虑了一段时间,但我真的不知道如何.

最佳答案 我不确定这是否是最干净的方法,但每当我这样做递归时,我经常会添加一个关键字参数,即要返回的列表.这样,当我修改列表时,我总是修改为相同的列表:

def recurse(max, _output=None):
    if _output is None:
        _output = []

    #do some work here, add to your list
    _output.append(max)

    if max <= 0: #Some condition where the recursion stops
        return _output
    else:        #recurse with new arguments so that we'll stop someday...
        return recurse(max-1, _output=_output)

这是有效的,因为当停止条件为True时,将返回_output列表并将其一直传递回堆栈.

我使用一个下划线变量名来表示它只能在函数本身中使用.这是使用下划线前缀变量的正常方式的略微扩展(在类中表示变量是“私有”),但我认为它得到了重点……

请注意,这与您的情况没有太大差别.但是,对于您的版本,结果将在调用之间保持,因为在创建函数时会计算result = [],而不是在调用函数时.此外,您的版本附加了返回值(列表本身).当您考虑列表中包含多个对自身的引用时,这会变得非常复杂……

点赞