メインコンテンツへスキップ

Summing Variables by Indices in Python

回答済み

コメント

1件のコメント

  • 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

サインインしてコメントを残してください。