'How to create an list of routes that come from a solution x[i,j]?
I'm trying to create an automatic method that, through a solution x[i,j] obtained in my model, manages to generate an list[list] of all routes, which collects each solution x, in each iteration, but without duplication.
Example:
routes = []
for i in range(N):
for j in range(N):
if x[i,j].x:
print(x[i,j])
routes.append([x[i,j]])
The solution obtained is the following:
<gurobi.Var x[0,1] (value 1.0)>
<gurobi.Var x[1,3] (value 1.0)>
<gurobi.Var x[3,0] (value 1.0)>
This solution is admissible, but I thought that by doing the routes.append([x[i,j]]) the array appeared in format routes=[[(0, 1), (1, 3), (3,0)]], that was the format that I would like to work, to be more simple.
Instead I get the result [[<gurobi.Var x[0,1] (value 1.0)>], [<gurobi.Var x[1,3] (value 1.0)>], [<gurobi.Var x[3,0] (value 1.0)>]], that doesn't help me.
Should I do it in another format?
By the way, can you help me to create a way, for each iteration and solution, to check the routes first and avoid duplicate insertion of the same route?
Solution 1:[1]
You're looking for the indexes where x[i,j] is 1. The code should look something like this:
routes = []
for i in range(N):
for j in range(N):
if x[i,j].x:
print(x[i,j])
routes.append((i,j))
Alternately, use Python list comprehension to create the list of routes:
routes = [(i,j) for i in range(N) for j in range(N) if x[i,j].X > 0.5]
And if x is a dictionary (or a Gurobi tupledict), you can simplify this to:
routes = [(i,j) for i,j in x.keys() if x[i,j].X > 0.5]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Greg Glockner |
