Python не будет запускать программу - PullRequest
0 голосов
/ 05 июля 2018

Я новичок в Python, но у меня есть опыт работы в колледже по C # и Matlab. Я пытаюсь написать и запустить алгоритм dijkstras, но когда я запускаю его, ничего не происходит. Я приложу код (включая закомментированные неудачные попытки) в надежде, что кто-то может направить меня в правильном направлении.

#must write script to turn matrix into this form of graph
graph = {'a':{'c':3,'e':5},'c':{'a':3,'d':5},'d':{'c':3,'e':6},'e':
{'d':6,'a':5}}
unseenNodes = {}
goal = {}
start = {}


#defining function
def dijkstra(graph, start, goal):
    shortest_distance = {} #empty dictionary
    predeccesor = {} #empty dictionary 
    unseenNodes = graph #makes it run through til all are seen
    path = []
def __init__(self):  
 #start node to next node
    print( str("hi"))

     for node in unseenNodes:
        shortest_distance[node]=9999999
        shortest_distance[start]=0
        print(shortest_distance)

#beefy bit of dijkstras alogrithim 
    while unseenNodes:
        minNode=None
        for node in unseenNodes:
            if minNode is None:
                minNode = node

            elif shortest_distance[node] < shortest_distance[minNode]:
                minNode = node

            for childNode, weight in graph [minNode].items():
                if weight + shortest_distance[minNode] < 
 shortest_distance[childNode]:
                    shortest_distance[childNode] = weight + shortest_distance[minNode]

                predeccesor[childNode] = minNode
                unseenNodes.pop(minNode)

                print(shortest_distance)

#reverse stack approach to trace path
    currentNode = goal
    while currentNode != start:
        try:
            path.insert(0,currentNode)
            currentNode = predeccesor[currentNode]
         except KeyError:
            print('path not valid')
        #break

        path.insert(0,start)
        if shortest_distance[goal] != infinity:
            #print(goal) 
            print('shortest distance is' + str(shortest_distance[goal]))
            print('path is' + str(path))
         else:
             Print('Something Went Wrong!')

#break

dijkstra(graph, 'a', 'd')

Ответы [ 3 ]

0 голосов
/ 05 июля 2018

Ваша функция dijkstra выполняет только эти четыре строки кода, так как они являются единственными строками кода до того, как вы определите вторую функцию. Поэтому, когда вы вызываете эту функцию в конце, программа создает несколько пустых словарей и затем закрывается:

shortest_distance = {} #empty dictionary
predeccesor = {} #empty dictionary 
unseenNodes = graph #makes it run through til all are seen
path = []

Вторая определяемая вами функция, init () - это метод класса, его нельзя определить вне класса.

Сначала взгляните на некоторые более простые алгоритмы в Python и ознакомьтесь с синтаксисом (я не знаю, насколько он отличается от C #).

0 голосов
/ 05 июля 2018

Вам нужно только одно изменение

  • Удалите это def __init__(self): function из кода.
  • функция __ init __ используется в class для инициализации переменные объекта.

  • Вы не можете вызвать __init__ функцию, поэтому вы не получили никакого вывода.

  • Также сделайте правильный отступ , вы получите свой вывод.
0 голосов
/ 05 июля 2018

ОК, поэтому я исправил кучу проблем с отступами, областями видимости и именами вашего кода (см. Ниже), и получил следующую ошибку

hi
{'a': 0}
{'a': 0, 'c': 9999999}
{'a': 0, 'c': 9999999, 'd': 9999999}
{'a': 0, 'c': 9999999, 'd': 9999999, 'e': 9999999}
{'a': 0, 'c': 3, 'd': 9999999, 'e': 9999999}
Traceback (most recent call last):
  File "dijkstras.py", line 69, in <module>
    dijkstra(graph, 'a', 'd')
  File "dijkstras.py", line 47, in dijkstra
    unseen_nodes.pop(minNode)
KeyError: 'a'

Возможно, это поможет вам продолжить?

#! /usr/bin/env python3
# dijkstras.py

import math

# must write script to turn matrix into this form of graph
graph = {
    'a': {'c': 3, 'e': 5},
    'c': {'a': 3, 'd': 5},
    'd': {'c': 3, 'e': 6},
    'e': {'d': 6, 'a': 5}
}


# defining function
def dijkstra(graph, start, goal):
    shortest_distance = {}  # empty dictionary
    predeccesor = {}  # empty dictionary
    unseen_nodes = graph  # makes it run through til all are seen
    path = []

    # start node to next node
    print(str("hi"))

    for node in unseen_nodes:
        shortest_distance[node] = 9999999
        shortest_distance[start] = 0
        print(shortest_distance)

    # beefy bit of dijkstras alogrithim
    while unseen_nodes:
        min_node = None
        for node in unseen_nodes:
            if min_node is None:
                min_node = node

            elif shortest_distance[node] < shortest_distance[min_node]:
                min_node = node

            for childNode, weight in graph[min_node].items():
                if weight + shortest_distance[min_node] < shortest_distance[childNode]:
                    shortest_distance[childNode] = weight + shortest_distance[min_node]

                    predeccesor[childNode] = min_node
                    unseen_nodes.pop(min_node)

                    print(shortest_distance)

                    # reverse stack approach to trace path
    current_node = goal
    while current_node != start:
        try:
            path.insert(0, current_node)
            current_node = predeccesor[current_node]
        except KeyError:
            print('path not valid')
        # break

        path.insert(0, start)
        if shortest_distance[goal] != math.inf:
            # print(goal)
            print('shortest distance is' + str(shortest_distance[goal]))
            print('path is' + str(path))
        else:
            print('Something Went Wrong!')



if __name__ == '__main__':  # only run if script
    dijkstra(graph, 'a', 'd')
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...