How to implement a graph from an input text file in python? -


i have input file of format:

stuttgart nuremberg 207 nuremberg munich 171 manchester birmingham 84 birmingham bristol 85 birmingham london 117 end of input 

i want apply brute force algorithm find shortest path (distance) between 2 cities need convert text graph. again, graph needs made dynamically, should work or other input file same format.

edit:: answer helped counting line "end of input" modified code :

i tried add while loop this:

      graph = {}       filename = open('input1.txt', 'r')       line in filename:           while line != "end of input" :               node1, node2, d = line.split()               graph.setdefault(node1, []).append((node2, d))               graph.setdefault(node2, []).append((node1, d))  # undirected  

graph

but working first 2 lines. wrong?

there many ways represent graph 1 of simplest dictionary of nodes list of edges, e.g.:

{   'stuttgart': [('nuremberg', 207)],   'nuremberg': [('munich', 171)],   'manchester': [('birmingham', 84)],   'birmingham': [('bristol', 85), ('london', 117)] } 

if undirected graph need add inverse of edges, e.g.:

  'nuremberg': [('stuttgart', 207), ('munich', 171)], 

this should pretty easy structure work graph algorithms. problem, need decide if can track (visit node more once) , if graph connected (which example data isn't), decide on appropriate algorithm.

you can build graph file (strawman):

graph = {}   # or use defaultdict(list) open('<filename>', 'r') f:     l in f:          n1, n2, d = l.split()          graph.setdefault(n1, []).append((n2, d))          graph.setdefault(n2, []).append((n1, d))  # undirected graph 

there many libraries implement graph algorithms, check out networkx: https://networkx.github.io/ see if has need.


Comments

Popular posts from this blog

c# - Binding a comma separated list to a List<int> in asp.net web api -

Delphi 7 and decode UTF-8 base64 -

html - Is there any way to exclude a single element from the style? (Bootstrap) -