Skip to content

Fix duplicate-variable coefficients in LinExpr - #429

Merged
h-g-s merged 1 commit into
masterfrom
fix-linexpr-duplicate-vars
Sep 25, 2026
Merged

h-g-s merged 1 commit into
masterfrom
fix-linexpr-duplicate-vars

Conversation

@h-g-s

@h-g-s h-g-s commented Sep 24, 2026

Copy link
Copy Markdown
Contributor

What this fixes

Thank you to the contributor of #397 for finding and documenting this problem.

The current LinExpr constructor uses dict(zip(variables, coeffs)). If the same variable appears more than once, earlier coefficients are silently lost. This can affect direct LinExpr construction as well as expressions involving identical variables.

This PR fixes the problem in the constructor itself by adding duplicate coefficients together. It keeps the fast path for the usual case where variables are unique.

It also adds tests for duplicate variables, including direct construction with three repeated entries.

Tests: 68 passed, 1 skipped.

Could you please check whether these cases fix the problem you reported in #397?

…uctor

Issue #396 / PR #397: constructing a LinExpr directly with a variables
list containing the same Var more than once (e.g. via Var.__add__,
Var.__sub__, Var.__eq__/__le__/__ge__ on identical objects, or manual
LinExpr(variables=..., coeffs=...) calls) silently kept only the last
coefficient because dict(zip(...)) overwrites duplicate keys.

PR #397's approach patches this only for the specific case where a Var
is combined with itself in a handful of dunder methods, and explicitly
does not fix direct constructor calls with 3+ duplicate entries (see
its commented-out test case).

This fixes the root cause in the LinExpr constructor itself, covering
all call sites. To avoid regressing performance for the common
duplicate-free case, a cheap len(variables) == len(set(variables))
check picks the fast dict(zip(...)) path when there are no duplicates,
falling back to an accumulating loop only when needed.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@h-g-s
h-g-s merged commit 50f00c9 into master Sep 25, 2026
58 of 61 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant