如何在Python的递归函数中返回列表列表
我正在玩弄Python中的一些玩具代码。但不知何故,我无法通过。我在树数据结构中使用递归来生成从特定节点到每个子叶节点的路径 递归函数背后的思想是有一个列表,该列表将收集到单个叶节点的每个路径,然后在另一个列表中收集每个路径如何在Python的递归函数中返回列表列表,python,python-2.7,recursion,Python,Python 2.7,Recursion,我正在玩弄Python中的一些玩具代码。但不知何故,我无法通过。我在树数据结构中使用递归来生成从特定节点到每个子叶节点的路径 递归函数背后的思想是有一个列表,该列表将收集到单个叶节点的每个路径,然后在另一个列表中收集每个路径 class Tree: def __init__(self): self._ancestors = [] self._store_nodes = {} def add_node(self, node): as
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 "-----"
我期望的结果是节点2的列表列表,如下所示:
path = [[10], [11], [5, 21], [5, 22], [5, 23]]
如何更正递归函数 这里有两种方法可以实现这个目标。我不太清楚如何修复你的结构;从头开始似乎更容易
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
为什么需要两个类来显示递归函数中的问题。请做一个,专注于极小值,你也叫它树,但如果我读对了你的节点存储,这是一个有向无环图,不是一回事。你说得对,修剪,这是一个DAG。我会尽量使用正确的命名法。谢谢你的指点。非常感谢你,贾里德,所有这些有价值的评论和代码片段都很有启发性。