2013-06-21 120 views
-1

问题是:这段代码可以优化吗?

有一条铁路通往一个城镇的不同城镇。由于预算问题,认为 铁路是单向的。如果有城市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 
+0

http://en.wikipedia.org/wiki/Shortest_path_problem可能会帮助 – akonsu

+0

@akonsu我不想要最短路径...我只想要总路径.. – sundar

+2

那么你是什么意思的“优化”? – Ant

回答

1

夫妇快的事情,当你想运行一个无限循环,并有它特定的事件打破,有没有需要申报和严格修改变量以此目的。 您只需启动你的while循环,这样

while True: 

,结束他们这样

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

通知的.lower在变量的末尾。这将强制用户输入为小写,所以您的支票将同时记录“Y”和“y”,这可能会有所帮助。

+0

是不是'.lower()'? – 2rs2ts

+1

这需要'y.lower()'。 –

+1

我个人认为这是值得怀疑的。作为一名外行,我认为证明带有变量的'while'循环终止,比具有'True'和'break'的循环更容易。 – akonsu