Reputation: 13
I am solving this simple question, I'm using recursive DFS to find the minimum path sum.
I wrote a global min_sum to allow me keeping track of the current minimum. Yet, after adding global
to my variable inside the dfs function, error message showed.
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))
But it shows: NameError: global name 'min_sum' is not defined
Upvotes: 0
Views: 657
Reputation: 4630
Please change global min_sum
to nonlocal min_sum
.
Note: Python 3
introduced the nonlocal
keyword that allows us to assign to variables in an outer, but non-global, scope.
Upvotes: 2