如何在Python中返回递归函数中的列表列表

时间:2017-07-05 16:53:14

标签: python python-2.7 recursion

我正在玩Python中的一些玩具代码。但不知何故无法通过。我在Tree数据结构中使用递归来生成从特定节点到每个子叶节点的路径。

递归函数背后的想法是有一个列表,它将收集到单个叶节点的每个路径,然后收集另一个列表中的每个路径。

class Tree:
    def __init__(self):
        self._ancestors = []
        self._store_nodes = {}

    def add_node(self, node):
        assert isinstance(node, Node)
        self._store_nodes[node.name] = node

    def get_c_path(self, node):
        subpath = []
        path = []
        path = self.ret_path(node, subpath, path)
        return path

    ## recursive function to fetch paths
    def ret_path(self, node, subpath=[], pathstore=[]):
        if len(node.children) ==  0:
            pathstore.append(subpath)
            return
        else:
            for c in node.children:
                subpath.append(c)
                self.ret_path(c, subpath, pathstore)

class Node(object):
    def __init__(self, name=''):
        self._name = name
        self._children = set([])
        self._parents = set([])

    @property
    def name(self):
        return self._name

    @property
    def children(self):
        return self._children

    @property
    def parents(self):
        return self._parents

    def add_child(self, node):
        assert isinstance(node, Node)
        self._children.add(node)

    def add_parent(self, node):
        assert isinstance(node, Node)
        self._parents.add(node)

if __name__ == '__main__':
    node_store = {1 : [2,3,4,5,6], 6 : [7,2,8,9,5], 2 : [10,11,5], 12 : [13,14,15,16], 5 : [21,22,23]}
    tree = Tree()
    ## build the tree and set parents and children of each node
    for k, v in node_store.items():
        parent_node = None
        if k in tree._store_nodes:
            parent_node = tree._store_nodes[k] 
        else:
            parent_node = Node(k)
            tree.add_node(parent_node)
        for c in v:
            child_node = None
            if c in tree._store_nodes:
                child_node = tree._store_nodes[c] 
            else:
                child_node = Node(c)
                tree.add_node(child_node)
            parent_node.add_child(child_node)
            child_node.add_parent(parent_node)

    print '-------------'
    path = tree.get_c_path(tree._store_nodes[2])
    for p in path:
        for t in p:
            print t.name
        print "-----"

我期望的结果是Node-2的列表列表如下:

 path  = [[10], [11], [5, 21], [5, 22], [5, 23]]

如何更正递归函数?

1 个答案:

答案 0 :(得分:0)

这是实现这一目标的两种方法。我不太确定如何修复你的结构;从头开始似乎更容易。

def get_c_path(self, node):
    branches = [[c] for c in node.children]
    expanded = self.expand_branches(branches)

    while branches != expanded:
        branches = expanded
        expanded = self.expand_branches(expanded)

    return expanded

def expand_branches(self, branches):
    new_branches = []
    for branch in branches:
        last_node = branch[-1]
        if last_node.children:
            for child in last_node.children:
                new_branches.append(branch + [child])
        else:
            new_branches.append(branch)
    return new_branches