【问题标题】:"Not in function" error in recursive function递归函数中的“不在函数中”错误
【发布时间】: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


【解决方案1】:

您当前的代码有 2 个问题,

  1. 你当前不计算根节点
  2. 如果没有孩子,则返回 1,在这种情况下,您应该返回 0。我们同样需要计算每个级别的孩子的数量,所以nodes_so_far应该用孩子列表的长度来初始化

修正这些,函数变为:

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 0 # There are no child so return 0 in base case
        else:
            nodes_so_far = len(childs) # set to number of nodes passed
            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 = 1 + recursive_node_count(root) # Add 1 to count the root node
    return total_nodes

在试运行中,这给出了输出:

>>> tree = {0: [1], 1: [2], 2: [3, 4], 3: None, 4: None, 'root': 0}
>>> tree_nodes(tree)
5

【讨论】:

  • 问题是关于正在打印的错误,这不能回答所问的问题。
  • @TylerCloutier 好吧,感谢您的反对,但我相信这可以很好地解决 OP 的问题,因此这里是一个有效的答案。
  • 甚至不清楚这里的问题是什么,但你说 2 暗示它们是异常的原因。实际上,这些只会影响返回的节点数,但不会导致问题。此外,这实际上只是一个问题,而不是两个问题。如果没有子节点,代码可以返回 1 个节点。真正应该改变的是从 1 开始 nodes_so_far。因此根被隐式计算。
  • 谢谢,这是一个完全有效的答案。我赞成你的回答。我会做你建议的改变,并告诉它是否解决了问题。提前致谢!
  • @renatov 参考docs.python.org/2.7/library/pdb.html。使用pdb.set_trace() 调用来检查代码的每个部分。您可以使用其中的多个(这些类似于断点语句),并在每个 for 循环之后检查前面步骤的输出是否正确。我知道错误指向递归,但它是一大段代码,python 的错误跟踪有时(很少)会产生误导。
【解决方案2】:

您的回答遗漏了几件事。这是围绕您的代码编写的固定版本:

def tree_nodes(tree):
    def recursive_node_count(node):
        if node is None:
            return 0
        total_nodes = 1
        if tree[node]:
            for child in tree[node]:
                if child:
                    total_nodes += recursive_node_count(child)
        return total_nodes

    root = tree['root']
    total_nodes = recursive_node_count(root)
    return total_nodes

>>> tree = {0: [1], 1: [2], 2: [3, 4], 3: None, 4: None, 'root': 0}
>>> print tree_nodes(tree)
5

【讨论】:

    【解决方案3】:

    鉴于您提供的代码,我无法重现该错误。它在语法上没有任何问题,并且确实运行良好。如果您可以更深入地了解您遇到的错误,我将编辑我的答案。

    话虽如此,正如 mu 所指出的,此代码将返回不正确的节点数。具体来说,它将返回树的叶子数,因为如果当前节点没有任何子节点,则仅计算当前节点。这个问题可以通过将nodes_so_far初始化为代表当前节点的1来解决。

    作为建议,您可能希望将for in xrange python 语句切换为普通的for in 语句。 for in 语句遍历列表,这样您就不必用 in 索引号重新索引到列表中。

    下面的代码说明了这些变化。此代码将始终输出正确数量的节点,即使在只有一个节点即根节点的情况下也是如此。

    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 not childs:
                # Return 1 for the current node.
                return 1
            else:
                # Initialize to 1 to count the current node.
                nodes_so_far = 1
                # Python for in statement
                for child in childs:
                    nodes_for_child = recursive_node_count(child)
                    nodes_so_far += nodes_for_child
                return nodes_so_far
        root = tree['root']
        total_nodes = recursive_node_count(root)
        return total_nodes
    
    print(tree_nodes(tree={0: [1], 1: [2], 2: [3, 4], 3: None, 4: None, 'root': 0}))
    print(tree_nodes(tree={0: None, 'root': 0}))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-05
      • 2015-06-01
      • 2019-07-02
      • 2019-11-16
      相关资源
      最近更新 更多