【发布时间】:2015-04-19 05:21:02
【问题描述】:
我正在编写一个算法来计算树的节点总数。这是代码:
def tree_nodes(tree):
"""Given a tree, returns the total amount of nodes it has."""
def recursive_node_count(node):
"""Recursive count function."""
childs = tree[node]
if childs == None:
return 1
else:
nodes_so_far = 0
for i in xrange(len(childs)):
nodes_in_this_branch = recursive_node_count(childs[i])
nodes_so_far += nodes_in_this_branch
return nodes_so_far
root = tree['root']
total_nodes = recursive_node_count(root)
return total_nodes
tree 基本上是一个列表字典。示例:
tree = {0: [1], 1: [2], 2: [3, 4], 3: None, 4: None, 'root': 0}
当我尝试运行我的代码时,这是我收到的输出:
at Answer.py. not in a function on line 31
at Answer.py. in recursive_node_count on line 31
at Answer.py. in recursive_node_count on line 31
at Answer.py. in recursive_node_count on line 31
at Answer.py. in recursive_node_count on line 31
at Answer.py. in recursive_node_count on line 31
at Answer.py. in recursive_node_count on line 31
at Answer.py. in recursive_node_count on line 31
at Answer.py. in recursive_node_count on line 31
at Answer.py. in recursive_node_count on line 31
at Answer.py. in tree_nodes on line 36
at Answer.py. in <module> on line 96
这些是原始代码中的31(在函数定义中)、36(也在定义中)和96(对定义的调用):
31: nodes_in_this_branch = recursive_node_count(childs[i])
36: total_nodes = recursive_node_count(root)
96: nodes = tree_nodes(tree)
我检查了语法、缩进、制表符、空格,但找不到错误。我是 Python 的初学者。大家能帮帮我吗?
【问题讨论】:
-
我无法重现您遇到的错误,是否在您在输出中发布的内容之前打印了一些内容?
-
这里是完整的代码:pastebin.com/mDyPPytn
-
顺便说一句,您的问题的答案是之前没有打印任何内容。整个代码在它的最后一行打印出来。
-
嗯,当我从 pastebin 运行所有代码时,我得到一个异常
struct_row(在第 80 行)未定义,实际上它在此之前没有分配。你能给我导致上述错误的示例输入吗? -
我没有得到你得到的错误,但我确实得到了最大递归深度超出错误。这可能是由于实际上有一棵比 python 的默认递归深度更深的树,在这种情况下,更可能是在你的树中有一个循环。例如
tree = {0: [1], 1: [0], 'root': 0}会导致无限递归。我怀疑这是你错误的真正原因。 (我增加了最大递归深度以确保这不是原因。)这种情况下所需的更改超出了这个问题的范围。
标签: python function recursion tree