почему я получаю ошибку ключа '' в python, используя словарь - PullRequest
0 голосов
/ 23 января 2020

Я использую алгоритм Дейкстры и получаю эту ошибку:

Not Checked: ['Bank', 'Blackfriars', 'Cannon Street', 'Chancery Lane', 'Charing Cross', 'Covent Garden', 'Embankment', 'Goodge Street', 'Holborn', 'Leicester Square', 'London Bridge', 'Mansion House', 'Monument', "St Paul's", 'Temple', 'Tottenham Court Road', '']
return self.func(*args)
  child_cost = graph[node]
KeyError: ''

Я использую чужой код на практике, но только что изменил его. Я делаю пробирку, используя tkinter, и это основной код. Пользователь выбирает начальную и конечную станции из двух OptionMenus, и при нажатии кнопки запускается алгоритм.

costs = {}
parents = {}
for node in graph:
    costs[node] = inf
    parents[node] = {}

costs[start.get()] = 0


def run_algorithm():
    def find_cheapest_node(costs, not_checked):
        cheapest_node = None
        lowest_cost = inf
        for node in not_checked:
            if costs[node] <= lowest_cost:
                lowest_cost = costs[node]
                cheapest_node = node
        return cheapest_node

    if __name__ == "__main__":
        not_checked = [node for node in costs]
        node = find_cheapest_node(costs, not_checked)
        while not_checked:
            print(f"Not checked: {not_checked}")
            cost = costs[node]
            child_cost = graph[node]
            for c in child_cost:
                if costs[c] > cost + child_cost[c]:
                    costs[c] = cost + child_cost[c]
                    parents[c] = node

            not_checked.pop(not_checked.index(node))
            node = find_cheapest_node(costs, not_checked)

        print(f"Costs: {costs}")
        print(f"The costs to go from {start} to {stop} is {costs[stop]}!")

        if costs[stop] < inf:
            path = [stop]
            i = 0
            while start not in path:
                path.append(parents[path[i]])
                i += 1

            print(f"The shortest path is {path[::-1]}")
        else:
            print("A path could not be found")

    print('route found')

Это мой график. Последняя станция в моем словаре - Дорога к Тоттенхэму, но там много кода.

import tkinter as tk
root = tk.Tk()
startnode = tk.StringVar()
endnode = tk.StringVar()

......

graph = {}

graph["Bank"] = {}
graph["Bank"]["London Bridge"] = 1
graph["Bank"]["St Paul's"] = 1

graph["Blackfriars"] = {}
graph["Blackfriars"]["Mansion House"] = 1
graph["Blackfriars"]["Temple"] = 1
...