Python最短距离

时间:2012-09-28 21:54:26

标签: python map shortest

我想编写一个程序,它返回从A点到E点的最短距离。我编码得到了长度,但我无法弄清楚如何实际得到这些点。

enter image description here

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))) )

输入的答案:shortestPath([“A”,“B”,“C”,“D”,“E”],d)是10.但是程序也应该把距离放好,所以答案应该是[10,[“A”,“C”,“D”,“E”]]

2 个答案:

答案 0 :(得分:1)

看起来像是一个典型的最短路径问题。 显而易见的方法是使用dijkstra,但有更酷的算法。 例如,我在codegolf会话中攻击了这个:

G,S,T=input();J={n:9e9if n!=T else 0for n in G}
while J[S]>1e9:J={n:0if n==T else min(c+J[d]for d,c in G[n].items())for n in G}
while S!=T:print S;S=min((c+J[d],d)for d,c in G[S].items())[1]

你必须改变你的图形表示,但它输出了这个输入的正确最短路径(你的复述图):

{'A': {'C': 3, 'B': 1, 'D': 7}, 'C': {'A': 3, 'B': 42, 'E': 13, 'D': 2}, 'B': {'A': 1, 'C': 42, 'E': 27, 'D': 6}, 'E': {'C': 13, 'B': 27, 'D': 5}, 'D': {'A': 7, 'B': 6, 'E': 5}}, 'A', 'E'

所以......阅读图算法,它们并不那么难。 如果你拒绝这样做:祝你理解我的代码转换修复点算法。

答案 1 :(得分:1)

如果您决定将其保存在一条内容中,则可以对代码进行少量更改:

def track_past_city(x,y):
    return (x[0]+y[0],x[1:]+y[1:]) #0 is how far you've gone, #[1:] is where you've been

def shortestPath(Cities,Distances):
    if len(Cities)==1: return 0, Cities[0]
    else: return min( map( lambda n: (track_past_city((Distances[Cities[0],Cities[n]],Cities[0]),shortestPath(Cities[n:],Distances))), range(1,len(Cities))) )


shortestPath(["A","B", "C", "D", "E"],d)
# (10, ('A', ('C', ('D', 'E'))))

我不是相当确定如何在错误的元组添加发生的地方,但是从这个你应该能够调整自己的解决方案......

注意:这带有健康警告,您不应该将所有代码写在一行上,它很难阅读,难以调试并且通常是一个坏主意。