Skip to content
Advertisement

How to compare a list of routes with a dictionary of costs between arcs?

Hello to the whole community,

I have a question about creating an automatic method (function or loop+) to declare a route cost variable, which involves the sum of each of the c_i,j arcs.

Example:

routes=[[(0, 1), (1, 2), (2, 0)],[(0, 1), (1, 0)],[(0, 2), (2, 0)]]  #  list of 3 possible routes in 2 locations where 0 is depot

cij = {(0,1): 3,(0, 2): 4,(0, 3): 5,(1, 0):3,(1, 2):5,(1, 3):7 ,(2, 0):4,(2, 1):5, (2, 3):9}  # dictionary with cost matrix between the arcs [i,j]

I would like to get help to reach a RouteCost variable that compares the list with the dictionary and will add each of the arcs it finds per route. For example, there would be a list of costs for the 3 routes:

RouteCost= [12,6,8]

Thank you for your help and keep up the good work to all.

Advertisement

Answer

This can be performed using a nested list comprehension:

RouteCost = [sum([cij[path] for path in route]) for route in routes]
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement