Skip to main content

Summing Variables by Indices in Python

Answered

Comments

2 comments

  • Official comment
    Simranjit Kaur
    • Gurobi Staff
    This post is more than two 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 try Gurobot, our chatbot interface offering instant, expert-level support.
  • Eli Towle
    • Gurobi Staff

    This depends on how you define the \(x\) variables in Python. I'll provide two examples. In both examples, I'll assume the variables are indexed \(0\) to \(99\) instead of \(1\) to \(100\).

    If you add the variables via Model.addVars(), you can sum over the desired indices using the quicksum() function, then add the constraint with Model.addConstr():

    x = m.addVars(100, name="x")
    m.addConstr(gp.quicksum(x[j] for j in range(i, 100)) <= 10)

    If you add the variables via Model.addMVar(), you can slice the MVar object to only include the desired indices, then call MVar.sum() on the result. The constraint is again added via Model.addConstr():

    x = m.addMVar((100,), name="x")
    m.addConstr(x[i:].sum() <= 10)
    0

Post is closed for comments.