Constraints with For loop
AnsweredCan I add or define a constraints inside a FOR loop. I am using python interface
0
-
Official comment
Dear Parijat,
That's indeed possible. Please find below an assignment problem I implemented with the Gurobi-Python interface:
import gurobipy as gp
from gurobipy import GRB
resources = ["r1", "r2", "r3"]
jobs = ["j1", "j2", "j3"]
costs = {("r1","j1"):1,("r1","j2"):2,("r1","j3"):3,
("r2","j1"):2,("r2","j2"):2,("r2","j3"):2,
("r3","j1"):3,("r3","j2"):2,("r3","j3"):1}
model = gp.Model("assignment")
assign = model.addVars(resources, jobs, vtype=GRB.BINARY, name="assign")
#model.addConstrs((assign.sum(r,"*") == 1 for r in resources), name="supply")
for r in resources:
model.addConstr(assign.sum(r,"*") == 1, name=f"supply[{r}]")
#model.addConstrs((assign.sum("*", j) == 1 for j in jobs), name="demand")
for j in jobs:
model.addConstr(assign.sum("*", j) == 1, name=f"demand[{j}]")
model.setObjective(assign.prod(costs), GRB.MINIMIZE)
model.optimize()I suggest you to check the functional code examples we provide in our website (please see here).
-
Official comment
This post is more than three years old. Some information may not be up to date. For current information, please check the Gurobi Documentation or Knowledge Base. If you need more help, please create a new post in the community forum. Or why not try our AI Gurobot?.
Post is closed for comments.
Comments
2 comments