我想编写一个程序,返回从 A 点到 E 点的最短距离。我编写了代码来获取长度,但我不知道如何实际获取这些点。
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"]]