0

I have a Dijkstra’s algorithm. When I run this portion of my script:

graph = {}

graph["begin"] = {}

graph["begin"]["a"] = 6

graph["begin"]["b"] = 2 

graph["begin"]["c"] = 3

graph["begin"]["d"] = 1 

graph["a"] = {}

graph["a"]["c"] = 3

graph["b"] = {}

graph["b"]["a"] = 3

graph["b"]["d"] = 5

graph["d"] = {}

graph["d"]["fin"] = 1

graph["c"] = {}

graph["c"]["d"] = 1

graph["c"]["fin"] = 3

graph["fin"] = {} 


infinity = float("inf")

costs = {}

costs["a"] = 6

costs["b"] = 2

costs["c"] = infinity 

costs["d"] = infinity

costs["fin"] = infinity 


parents = {}

parents["a"] = ["begin"]

parents["b"] = ["begin"]

parents["c"] = ["begin"]

parents["d"] = ["begin"]

parents["fin"] = None 



processed = [] 

def find_lowest_cost_node(costs):

  lowest_cost = float("inf")

  lowest_cost_node = None

  for node in costs:

    cost = costs[node]

    if cost < lowest_cost and node not in processed:

      lowest_cost = cost

      lowest_cost_node = node

  return lowest_cost_node


def run_dijkstra():

  node = find_lowest_cost_node(costs)

  while node is not None:

    neighbors = graph[node]

    for neighbor in neighbors.keys():

      newcost = neighbors[neighbor] + costs[node]

      if newcost < costs[neighbor]:

        costs[neighbor] = newcost

        parents[neighbor] = node

    processed.append(node)

    node = find_lowest_cost_node(costs)

  return 

  def print_path(begin, fin):
print ["cost to destination", str(costs["fin"])]

     print ["fin"]

  nextNode = parents[end]

  while nextNode != begin:

    print ["nextNode"]

    nextNode = parents[nextNode]

  print ["begin"]


run_dijkstra()

print_path("begin, end")

I get this error message:

Traceback (most recent call last): File "python", line 70, in NameError: name 'print_path' is not defined

Does anyone know a decision of this problem?)

1

Check the alignment within the print_path(begin, end) function (possibly a copy/paste issue, but as it is it will not work)

The function declaration is print_path(begin, end), but it is called as print_path("begin, end"), so with a single string argument. Try print_path("begin", "end")

  • Also, make sure your indentations are correct after the function def statement. – artwork21 Nov 21 '18 at 16:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.