我想寫一個程序,返回從點A到點E的最短距離。我編碼得到的長度,但我不知道如何實際得到的點。Python的最短距離
d = {("A","A"):0, ("A","B"):1, ("A","C"):3, ("A","D"):7 , ("A","E"):101,
("B","A"):101, ("B","B"):0, ("B","C"):42, ("B","D"):6, ("B","E"):27,
("C","A"):101, ("C","B"):101, ("C","C"):0, ("C","D"):2, ("C","E"):13,
("D","A"):101, ("D","B"):101, ("D","C"):101, ("D","D"):0, ("D","E"):5,
("E","A"):101, ("E","B"):101, ("E","C"):101, ("E","D"):101, ("E","E"):0
}
def shortestPath(Cities,Distances):
'''Returns the length of the shortest path from the first city in the list to the last city in the list, using only cities that appear in that list.'''
if len(Cities)==1: return 0
else: return min(map(lambda n: (Distances[Cities[0],Cities[n]] + shortestPath(Cities[n:],Distances)), range(1,len(Cities))))
答案輸入:最短路徑([ 「A」, 「B」, 「C」, 「d」, 「E」],d)是10。但是該程序也應該輸出距離,所以答案應該是[10,[「A」,「C」,「D」,「E」]]
所以...你希望我們調試你的程序?或者你的具體問題是什麼?你是否自己做了一些調試,比如看看'map'的結果是什麼? –
爲什麼你用這種方式編寫最短路徑算法?它是強制性的嗎?否則,您可以使用[Dijkstra的SPA](http://en.wikipedia.org/wiki/Dijkstra's_algorithm#Pseudocode),因爲有一種簡單的方法來重新創建最短路徑。 –