未定义全局名称“ NAME”

时间:2019-09-13 06:52:16

标签: python global

我正在解决这个简单的问题,我正在使用递归DFS查找最小路径总和。

我写了一个全局min_sum来跟踪当前的最小值。然而,在dfs函数内的变量中添加global后,显示了错误消息。


def get_cheapest_cost(node):

    def dfs(node, route):

        global min_sum

        route.append(node.cost)

        if not node.children:
            min_sum = min(min_sum, sum(route))  

        for c in node.children:
            dfs(c, route)  
        route.pop()

    min_sum = float("inf")    
    dfs(node, [])
    return min_sum



########################################## 
# Use the helper code below to implement #
# and test your function above           #
##########################################

# A node 
class Node:

  # Constructor to create a new node
  def __init__(self, cost):
    self.cost = cost
    self.children = []
    self.parent = None


root = Node(0)
d1_1 = Node(5)
d1_2 = Node(3)
d1_3 = Node(6)
root.children = [d1_1, d1_2, d1_3]

d2_1 = Node(4)
d2_2 = Node(2)
d2_3 = Node(0)
d2_4 = Node(1)
d2_5 = Node(5)

d1_1.children = [d2_1]
d1_2.children = [d2_2, d2_3]
d1_3.children = [d2_4, d2_5]

d3_1 = Node(1)
d3_2 = Node(10)

d2_2.children = [d3_1]
d2_3.children = [d3_2]

d4_1 = Node(1)
d3_1.children = [d4_1]

d4_1 = Node(1)


print(get_cheapest_cost(root))


但它显示:NameError:全局名称'min_sum'未定义

2 个答案:

答案 0 :(得分:2)

请将global min_sum更改为nonlocal min_sum

注意:Python 3引入了nonlocal关键字,该关键字使我们可以在外部但非全局范围内分配变量。

答案 1 :(得分:-2)

声明全局变量。

min_sum = 0
def get_cheapest_cost(node):

    def dfs(node, route):

        global min_sum

        route.append(node.cost)

        if not node.children:
            min_sum = min(min_sum, sum(route))  

        for c in node.children:
            dfs(c, route)  
        route.pop()

    min_sum = float("inf")    
    dfs(node, [])
    return min_sum