问题是:这段代码可以优化吗?
有一条铁路通往一个城镇的不同城镇。由于预算问题,认为 铁路是单向的。如果有城市A,并且它有 城市B和C城市通过铁路公路相连,则A和公司有直接通往B和C公路的铁路不是强制性的。从A到C的路线可以是A到B,然后是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
http://en.wikipedia.org/wiki/Shortest_path_problem可能会帮助 – akonsu
@akonsu我不想要最短路径...我只想要总路径.. – sundar
那么你是什么意思的“优化”? – Ant