1
city=["A","B"] week=[0,1,2,3] S={"A":[5,15,25,35], "B":[80,11,31,30]} model=gp.Model() I = model.addVars(city, week, name="I") model.setObjective(...) # try 1: model.addConstrs(S[c][w] <= I[c][w] for c in city for w in week) # try 2: for c in city: for w in week: model.addConstr(S[c][w] <= I[c][w]) 

Hello, I am trying to solve a problem and I need to add a constraint for each city and for each week. However, I get a "SyntaxError: invalid syntax" for the for loop when trying to add the constraint. Could you help me I am not sure how to correctly add them?

1 Answer 1

2

Note that model.addVars() returns a gurobi tupledict where each key is stored as tuplelist:

>>> print(I) In [64]: I Out[64]: {('A', 0): <gurobi.Var I[A,0]>, ('A', 1): <gurobi.Var I[A,1]>, ('A', 2): <gurobi.Var I[A,2]>, ('A', 3): <gurobi.Var I[A,3]>, ('B', 0): <gurobi.Var I[B,0]>, ('B', 1): <gurobi.Var I[B,1]>, ('B', 2): <gurobi.Var I[B,2]>, ('B', 3): <gurobi.Var I[B,3]>} 

Hence, the expression I[c][w] yields a KeyError. Use I[c,w] or I[(c, w)] instead.

That said, your 'constraints' are just lower bounds for the variables; thus, there's no real need for constraints. You can just set the lower bounds for the variables:

for c in city: for w in week: I[c, w].lb = S[c][w] 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.