-1

I apologize in advanced, I don't really know python, but I'm trying to use it along with this networkx library to find the distances between "BOS" Boston airport to all the other airports I have in a text file. I have:

import networkx as nx

G = nx.Graph()

code = []
name = []
longitude = []
latitude = []

rows = 0
with open("airport_info.txt") as f:
    content = f.readlines()
    rows = len(content)
    for i in range(0, rows-1):
        columns = content[i].split(",")
        G.add_node(columns[0],pos=(float(columns[2]),float(columns[3].replace("\n",""))))

with open("flying_times.txt") as x:
    content = x.readlines()
    rows = len(content)
    for i in range(0,rows-1):
        columns = content[i].split(",")
        G.add_edge(columns[0],columns[1],weight=float(columns[2].replace("\n","")))

#print list(G.nodes())
#print list(G.edges())

#print nx.shortest_path_length(G,weight='weight')
print nx.shortest_path_length(G,"BOS")

This will give me the number of Nodes between BOS and every other airport, but how can I translate this into the actual distances (in hours) between BOS and each? Thanks!

1 Answer 1

0

You should use nx.dijkstra_path_length. In particular if you want to print all the nodes distances this is what you need.

for target in G.nodes_iter():
    if target != 'BOS':
        print("Distance 'BOS' to '%s': %f" %
              (target, nx.dijkstra_path_length(G, "BOS", target)))

If you want the path you can instead use nx.dijkstra_path.

I think you might also run in some issues because range is not returning the value passed as stop, so you might be reading one line less then you expect; you should use range(row) (the 0 can be omitted). Anyway that code is not very pythonic, if you prefer you can use the following code:

import networkx as nx

G = nx.Graph()
with open("airport_info.txt") as f:
    for line in f:
       code, lat, long = line.rstrip().split(",")
       G.add_node(code,pos=(float(lat),float(long)))

with open("flying_times.txt") as x:
    for line in x:
        source, target, distance = line.rstrip().split(",")
        G.add_edge(source, target, weight=float(distance))

for target in G.nodes_iter():
    if target != 'BOS':
        print("Distance 'BOS' to '%s': %f" %
              (target, nx.dijkstra_path_length(G, "BOS", target)))

Final consideration: you are using an undirected graph. This means that distances are always symmetric, and I don't know whether this is what you really need.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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