Tuesday 15 February 2011

python - Can this code be optimized more? -


The question was:

The question was:

There is a railway road for different cities from one city. It is believed that due to budgetary issues, the railways are the only way. If the city is A and the city B and C cities are connected to the railways, then it is not mandatory that A is a direct rail road for both B and C. The route for A to C can be A to B and then from B to C. The above scenario is shown as graph. Nodes are the towns and the edges are the distance between them.
The input given will also be a graph and path to the towns. There should be a distance of the total railway road between the towns and if there is no route, then there should be 'no route exists'.

  Input: AB5, BC2, CD3, B4 Input: Abe Input: ACE Output: 9 Output: No Route   

My The code is:

  print "Welcome to the Total Path Count Program" n = 1 inp = 1 graph = dict (while while (n == 1): Print "Enter 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 other: 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 "Total cost% d" except for% (t) Keyire: Print "No route exists Is "print" you want to find the cost for more connections? "X = raw_input () if x == 'y': inp = 1 other: inp = 0    < P> 

Couple fast things, when you want to run an infinite loop, and do this There is no need to strictly declare and modify for this purpose. You can start the loops of your time in such a way.

  While true: / Code>  

and end them like this

  y = Raw_input () if y.lower ()! = 'Y': break   

See .lower at the end of the variable. This will force user input in lower case, so your check will catch both "Y" and "y" which can be helpful.

No comments:

Post a Comment