2015-11-24 95 views
-1

我試圖讀取一個文件與源目標體重值分別找到最短的路徑和打印與最終重量的路徑。我使用Networkx來使用Dijkstra函數。然而,當我執行,我收到此通知:
<function shortest_path at 0x7f9a13c39230> <function bidirectional_dijkstra at 0x7f9a13c48140>Dijkstra的算法與Networkx的實現,顯示打印錯誤

我最初使用只是shortest_path功能思維不知何故,我搞砸了使用它,因此利用bidirectional_dijkstra功能。

有問題的文件虛擬數據example.txt的標題爲: D1 D5 7 D1 D2 6 D5 D4 7 D5 D3 7 D5 D3 3 D5 D2 4 D2 D2 1 D4 D3 1

我的方法在Python:

#!/usr/bin/env python 
import os.path 
import networkx as nx 
from sys import argv 


#!script, filename = argv 
#assigns example to open the file example.txt 
example = open("example.txt", "r") 

print("\n This is what we have in our file:\n") 

#prints the open file 
print example.read() 

G =nx.Graph() 

for line in example: 
    source, target, weight = line.split() 
    nx.shortest_path(G,[source, target, weight]) 

print (nx.shortest_path) 
print (nx.bidirectional_dijkstra) 
#for some reason, this is printing: 
# 
#<function shortest_path at 0x7fe480d56230> 
#<function bidirectional_dijkstra at 0x7fe480d65140> 
+0

你實際上沒有調用該函數。即'nx.shortest_path'是實際的函數,'nx.shortest_path()'會給你返回值。 –

+0

所以,我應該將'nx.shortest_path'改爲'nx.shortest_path()'? – Atychip

+0

那麼你想要打印什麼?看起來像你在while循環中正確調用它,但沒有捕獲返回值 –

回答

0

所以,我收到了,因爲我沒有正確定義的邊緣的消息。 這裏的更新代碼:

import os.path 
    import networkx as nx 
    from sys import argv 


    #!script, filename = argv 
    #assigns example to open the file example.txt 
    example = open("/example.txt", "r") 


    G =nx.Graph() 

    for line in example: 
     line = line.split() 
     G.add_edge(line[0], line[1], weight=line[2]) 
     #nx.shortest_path(G,[source, target, weight]) 

    print nx.shortest_path(G) 
    print nx.average_shortest_path_length(G)