@@ -30,18 +30,18 @@ def tsp(cost):
3030 """
3131 # create the adjacency list
3232 adj = create_list (cost )
33-
34- #check for triangle inequality violations
33+
34+ # check for triangle inequality violations
3535 if triangle_inequality (adj ):
3636 print ("Triangle Inequality Violation" )
3737 return - 1
3838
3939 # construct the travelling salesman tour
4040 tsp_tour = approximate_tsp (adj )
41-
41+
4242 # calculate the cost of the tour
4343 tsp_cost = tour_cost (tsp_tour )
44-
44+
4545 return tsp_cost
4646
4747
@@ -51,10 +51,10 @@ def approximate_tsp(adj):
5151
5252 # to store the cost of minimum spanning tree
5353 mst_cost = [0 ]
54-
54+
5555 # stores edges of minimum spanning tree
5656 mst_edges = find_mst (adj , mst_cost )
57-
57+
5858 # to mark the visited nodes
5959 visited = [False ] * n
6060
@@ -64,17 +64,17 @@ def approximate_tsp(adj):
6464 for e in mst_edges :
6565 mst_adj [e [0 ]].append ([e [1 ], e [2 ]])
6666 mst_adj [e [1 ]].append ([e [0 ], e [2 ]])
67-
67+
6868 # to store the eulerian tour
6969 tour = []
7070 eulerian_circuit (mst_adj , 0 , tour , visited , - 1 )
71-
71+
7272 # add the starting node to the tour
7373 tour .append (0 )
7474
7575 # to store the final tour path
7676 tour_path = []
77-
77+
7878 for i in range (len (tour ) - 1 ):
7979 u = tour [i ]
8080 v = tour [i + 1 ]
@@ -88,9 +88,10 @@ def approximate_tsp(adj):
8888
8989 # add the edge to the tour path
9090 tour_path .append ([u , v , weight ])
91-
91+
9292 return tour_path
9393
94+
9495def tour_cost (tour ):
9596 cost = 0
9697 for edge in tour :
@@ -109,7 +110,8 @@ def eulerian_circuit(adj, u, tour, visited, parent):
109110
110111 if visited [v ] == False :
111112 eulerian_circuit (adj , v , tour , visited , u )
112-
113+
114+
113115# function to find the minimum spanning tree
114116def find_mst (adj , mst_cost ):
115117 n = len (adj )
@@ -119,7 +121,7 @@ def find_mst(adj, mst_cost):
119121
120122 # stores edges of minimum spanning tree
121123 mst_edges = []
122-
124+
123125 pq = []
124126 heapq .heappush (pq , [0 , 0 , - 1 ])
125127
@@ -132,13 +134,13 @@ def find_mst(adj, mst_cost):
132134
133135 if visited [u ]:
134136 continue
135-
137+
136138 mst_cost [0 ] += weight
137139 visited [u ] = True
138140
139141 if parent != - 1 :
140142 mst_edges .append ([u , parent , weight ])
141-
143+
142144 for neighbor in adj [u ]:
143145 v = neighbor [0 ]
144146 if v == parent :
@@ -148,7 +150,6 @@ def find_mst(adj, mst_cost):
148150 if not visited [v ]:
149151 heapq .heappush (pq , [w , v , u ])
150152 return mst_edges
151-
152153
153154
154155# function to calculate if the
0 commit comments