I have a problem with the path of each truck. From my model, I get the output of each truck path is misorder. I would like to order my list of edges based on the start and endpoint.
trucks = {0: (10, 1),1:(7,1),2: (3, 10),3:(7,4)} # truck_number:(start_point, end_point)
input I need to change:
path = {0: [(2, 1), (5, 2), (6, 5), (10, 6)],
1: [(2, 1), (5, 2), (6, 5), (7, 6)],
2: [(2, 5), (3, 2), (5, 6), (6, 10)],
3: [(5, 4), (6, 5), (7, 6)]}
output I need
output_i_need ={0: [(10, 6), (6, 5), (5, 2), (2, 1)],
1: [(7, 6), (6, 5), (5, 2), (2, 1)],
2: [(3, 2), (2, 5), (5, 6), (6, 10)],
3: [(7, 6), (6, 5), (5, 4)]}
is there any library in python to order my list of edges?
CodePudding user response:
I don't know of a library, but writing a function to reorder the list of edges is easy if you convert the list of edges into a dictionary mapping edge_start to edge_end.
trucks = {0: (10, 1),1:(7,1),2: (3, 10),3:(7,4)} # truck_number:(start_point, end_point)
paths = {0: [(2, 1), (5, 2), (6, 5), (10, 6)],
1: [(2, 1), (5, 2), (6, 5), (7, 6)],
2: [(2, 5), (3, 2), (5, 6), (6, 10)],
3: [(5, 4), (6, 5), (7, 6)]}
def reordered(l, start, end):
d = dict(l)
result = []
while start != end:
result.append((start, d[start]))
start = d[start]
return result
new_paths = { truck: reordered(path, trucks[truck][0], trucks[truck][1])
for truck,path in paths.items() }
print(new_paths)
# {0: [(10, 6), (6, 5), (5, 2), (2, 1)],
# 1: [(7, 6), (6, 5), (5, 2), (2, 1)],
# 2: [(3, 2), (2, 5), (5, 6), (6, 10)],
# 3: [(7, 6), (6, 5), (5, 4)]}