質問は:
ある町から別の町への鉄道があります。鉄道は予算の問題から一方通行と考えられる。都市 A があり、都市 B と都市 C が鉄道で接続されている場合、A が B と C の両方に直接鉄道を持っている必要はありません。 . 上記のシナリオは、グラフとして表されます。ノードは町で、エッジはそれらの間の距離です。
与えられた入力はグラフであり、町へのルートでもあります。出力は町間の総鉄道距離である必要があり、ルートが存在しない場合は「ルートが存在しません」と表示される必要があります。
Input: AB5, BC2, CD3, BE4
Input: A-B-E
Input: A-C-E
Output: 9
Output: No Route Exists
私のコードは次のとおりです。
print "Welcome to the total path calculation program"
n=1
inp=1
graph=dict()
while(n==1):
print "Enter the connection:"
x=raw_input()
new={x[0]:{x[1]:x[2]}}
graph.update(new)
print "Do you want to enter another connection?"
y=raw_input()
if y=='y':
n=1
else:
n=0
while(inp):
print "Now enter the connection to find the total cost:"
x=raw_input()
try:
t=int(graph[x[0]][x[2]])+int(graph[x[2]][x[4]])
print "The total cost is %d" %(t)
except KeyError:
print "No route exists"
print "Do you want to find cost for more connections?"
x=raw_input()
if x=='y':
inp=1
else:
inp=0