Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/354.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python &引用;“功能不正常”;递归函数中的错误_Python_Function_Recursion_Tree - Fatal编程技术网

Python &引用;“功能不正常”;递归函数中的错误

Python &引用;“功能不正常”;递归函数中的错误,python,function,recursion,tree,Python,Function,Recursion,Tree,我正在写一个算法来计算一棵树的节点总数。代码如下: 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:

我正在写一个算法来计算一棵树的节点总数。代码如下:

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 = {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

我检查了语法、缩进、制表符、空格,但找不到错误。我是Python的初学者。你们能帮帮我吗?

你们当前的代码有两个问题

  • 您当前不计算根节点
  • 如果没有子级,则返回1,在这种情况下应返回0。同样,我们需要计算每个级别上的child数量,因此应使用child列表的长度初始化
    节点
  • 纠正这些错误后,功能变为:

    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
    

    您当前的代码有两个问题

  • 您当前不计算根节点
  • 如果没有子级,则返回1,在这种情况下应返回0。同样,我们需要计算每个级别上的child数量,因此应使用child列表的长度初始化
    节点
  • 纠正这些错误后,功能变为:

    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
    

    你的答案遗漏了几点。以下是围绕代码编写的固定版本:

    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
    

    你的答案遗漏了几点。以下是围绕代码编写的固定版本:

    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
    

    鉴于您提供的代码,我无法再现错误。它在语法上没有什么问题,而且确实运行良好。如果您能更深入地了解所遇到的错误,我将编辑我的答案

    也就是说,正如mu所指出的,该代码将返回不正确的节点数。具体地说,它将返回树的叶子数,因为只有当当前节点没有任何子节点时,才对其进行计数。通过将
    节点迄今为止
    初始化为表示当前节点的
    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}))
    

    鉴于您提供的代码,我无法再现错误。它在语法上没有什么问题,而且确实运行良好。如果您能更深入地了解所遇到的错误,我将编辑我的答案

    也就是说,正如mu所指出的,该代码将返回不正确的节点数。具体地说,它将返回树的叶子数,因为只有当当前节点没有任何子节点时,才对其进行计数。通过将
    节点迄今为止
    初始化为表示当前节点的
    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}))
    

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