可变对象的递归函数

问题描述 投票:1回答:1

我正在尝试在一个类中递归构建所有路径。这是我到目前为止的内容:

def get_paths(self, component=None, current_path=None, all_paths=None):

    # set defaults
    if component is None: 
        component = self._ground; 
        current_path = [component,]

    ##### [START] RECURSIVE PART #####

    # get parents of component
    parents = component.parents()

    # if no parents (an endpoint/leaf), add the current_path
    if not parents:
        all_paths.append(current_path)

    # if parents ==> recurse
    # note: because we're starting from the ground and getting all parents
    # we insert the parent before the current path (not after, like if we
    # were recursively getting files in a directory)
    else:
        for parent in parents:
            self.get_paths(parent, [parent,] + current_path), all_paths)

    ##### [END] RECURSIVE PART #####

    # Note that the recursion doesn't 'return' anything, it only modifies
    # the list. We still have to return the list by the method at the end.      
    return all_paths

这是从“地面”开始,然后递归直到元素没有任何父元素。我的问题是,这是否是递归的一种常用方法-实际上不返回“递归部分”中的任何内容,而只是修改可变元素(此处的列表),然后稍后返回结果。

如果上述方法不理想,将如何改进它?或者,还有什么其他方法可以返回路径列表(上面的方法与$ find ./会获得路径列表的方法非常相似)。

python python-3.x recursion
1个回答
1
投票

一种简单的方法是拥有一个调用私有递归方法的公共“接口”方法。

遵循这些原则:

class Klass:

    _ground = 'ground'

    # Public method.
    def get_paths(self, component=None, current_path=None):
        all_paths = []
        self._get_paths(all_paths, component, current_path)  # Call private method.
        return all_paths

    # Private method.
    def _get_paths(self, all_paths, component=None, current_path=None):
        # Modifies all_paths - executed for that side-effect.    

        # set defaults
        if component is None:
            component = self._ground;
            current_path = [component,]

        # get parents of component
        parents = component.parents()

        # if no parents (an endpoint/leaf), add the current_path
        if not parents:
            all_paths.append(current_path)
        else:
            for parent in parents:
                self._get_paths(parent, [parent,] + current_path), all_paths)
© www.soinside.com 2019 - 2024. All rights reserved.