ポイント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です。ただし、プログラムは距離も出力する必要があるため、実際には答えが必要です。 be [10、["A"、 "C"、 "D"、 "E"]]