-1

質問は:

ある町から別の町への鉄道があります。鉄道は予算の問題から一方通行と考えられる。都市 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
4

1 に答える 1

1

無限ループを実行し、特定のイベントで中断する場合、この目的のために厳密に変数を宣言して変更する必要はありません。このようにwhileループを開始するだけです

while True:

そして、このようにそれらを終了します

y=raw_input()
if y.lower() !='y':
    break

.lower変数の末尾にある に注意してください。これにより、ユーザー入力が小文字に強制されるため、チェックで "Y" と "y" の両方が検出されるため、役立つ場合があります。

于 2013-06-21T17:08:04.600 に答える