diff --git a/04_modelling.md b/04_modelling.md index f9d8c95..dbae64b 100644 --- a/04_modelling.md +++ b/04_modelling.md @@ -447,9 +447,9 @@ consider, although such scenarios are rare in practical applications. > [!TIP] > -> If you have long sums of variables and coefficients, it can be more efficient to -> use the sum-methods of LinearExpr than to use Python's sum-function. Note that -> this function does currently not support generators. +> If you have long sums of variables and coefficients, it can be more efficient +> to use the sum-methods of LinearExpr than to use Python's sum-function. Note +> that this function does currently not support generators. > > ```python > xs = [model.NewIntVar(0, 10, f"x{i}") for i in range(5)] diff --git a/README.md b/README.md index d431d92..dcc0625 100644 --- a/README.md +++ b/README.md @@ -885,6 +885,19 @@ multiplying all terms by 3. However, this requires manual intervention, which undermines the idea of using a solver. These limitations are important to consider, although such scenarios are rare in practical applications. +> [!TIP] +> +> If you have long sums of variables and coefficients, it can be more efficient +> to use the sum-methods of LinearExpr than to use Python's sum-function. Note +> that this function does currently not support generators. +> +> ```python +> xs = [model.NewIntVar(0, 10, f"x{i}") for i in range(5)] +> weights = [i for i in range(5)] +> model.add(cp_model.LinearExpr.sum(xs) >= 1) +> model.minimize(cp_model.LinearExpr.weighted_sum(xs, weights)) +> ``` + If you have a lower and an upper bound for a linear expression, you can also use the `add_linear_constraint`-method, which allows you to specify both bounds in one go. diff --git a/tests/test_lin_constraints.py b/tests/test_lin_constraints.py index 3a504df..e7a16db 100644 --- a/tests/test_lin_constraints.py +++ b/tests/test_lin_constraints.py @@ -20,14 +20,13 @@ def test_lin_constraints(): model.add(x < y + z) model.add(y > 300 - 4 * z) + def test_lin_constraint_sum(): model = cp_model.CpModel() vars = [model.NewIntVar(0, 10, f"x{i}") for i in range(5)] weights = [i for i in range(5)] model.add(cp_model.LinearExpr.sum(vars) >= 1) model.minimize(cp_model.LinearExpr.weighted_sum(vars, weights)) - - def test_infeasible_intersection():