Как передать Set (или сеть) в качестве аргумента в Python из командной строки - PullRequest
0 голосов
/ 25 марта 2019

Я не могу использовать IronPython до тех пор, пока он не будет одобрен, и мне сообщили, что это может занять довольно много времени, поэтому я пытаюсь заставить некоторые сетевые алгоритмы работать из командной строки, чтобы их можно было использовать в коде C #. Я пытаюсь передать сеть в качестве аргумента из командной строки. У меня проблема в том, что, когда я определяю график

 graph = {'s': {'a': 2, 'b': 1}, 'a': {'s': 3, 'b': 4, 'c':8}, 'b': {'s': 4, 'a': 2, 'd': 2}, 'c': {'a': 2, 'd': 7, 't': 4}, 'd': {'b': 1, 'c': 11, 't': 5}, 't': {'c': 3, 'd': 5}}

в коде Python, он отлично работает, и я получаю ответ, который хочу. Когда я пытаюсь отправить его в качестве аргумента:

C:\\Python27\\Python.exe C:\\PythonFiles\\DijkstraAlgorithm3.py  "{'s': {'a': 2, 'b': 1}, 'a': {'s': 3, 'b': 4, 'c':8}, 'b': {'s': 4, 'a': 2, 'd': 2}, 'c': {'a': 2, 'd': 7, 't': 4}, 'd': {'b': 1, 'c': 11, 't': 5}, 't': {'c': 3, 'd': 5}}"

Я получаю следующую ошибку:

Traceback (most recent call last):
File "C:\\PythonFiles\\DijkstraAlgorithm3.py", line 60, in <module>
dijkstra(args.g,'s','t')
File "C:\\PythonFiles\\DijkstraAlgorithm3.py", line 27, in dijkstra
for neighbor in graph[src] :
TypeError: string indices must be integers, not str

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

import argparse

def dijkstra(graph,src,dest,visited=[],distances={},predecessors={}):
    # a few sanity checks
    if src not in graph:
        raise TypeError('The root of the shortest path tree cannot be found')
    if dest not in graph:
        raise TypeError('The target of the shortest path cannot be found')    
    # ending condition
    if src == dest:
        # We build the shortest path and display it
        path=[]
        pred=dest
        while pred != None:
        path.append(pred)
            pred=predecessors.get(pred,None)
        print('shortest path: '+str(path)+" cost="+str(distances[dest])) 
    else :     
        # if it is the initial  run, initializes the cost
        if not visited: 
            distances[src]=0
        # visit the neighbors
        for neighbor in graph[src] :
            if neighbor not in visited:
                new_distance = distances[src] + graph[src][neighbor]
                if new_distance < distances.get(neighbor,float('inf')):
                    distances[neighbor] = new_distance
                    predecessors[neighbor] = src
        # mark as visited
        visited.append(src)
        # now that all neighbors have been visited:    
    recurse                         
        # select the non visited node with lowest distance 'x'
        # run Dijskstra with src='x'
        unvisited={}
        for k in graph:
            if k not in visited:
                unvisited[k] = distances.get(k,float('inf'))        
        x=min(unvisited, key=unvisited.get)
        dijkstra(graph,x,dest,visited,distances,predecessors)



if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument('g', help='This is the network')
    # Parse the given arguments
    args = parser.parse_args()
    graph = {'s': {'a': 2, 'b': 1}, 'a': {'s': 3, 'b': 4, 'c':8}, 'b': {'s': 4, 'a': 2, 'd': 2}, 'c': {'a': 2, 'd': 7, 't': 4}, 'd': {'b': 1, 'c': 11, 't': 5}, 't': {'c': 3, 'd': 5}}
    #print args.g
    #print graph
    dijkstra(args.g,'s','t')
...