Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions pulp/core/lp_affine_expression.py
Original file line number Diff line number Diff line change
Expand Up @@ -158,10 +158,10 @@ def __contains__(self, key: LpVariable) -> bool:
return key in self.keys()

def get(self, key: LpVariable, default: float | None = None) -> float | None:
try:
return self[key]
except KeyError:
# self[key] returns 0.0 for a variable that is not in the expression
if key not in self:
return default
return self[key]

def isAtomic(self) -> bool:
return len(self) == 1 and self.constant == 0 and next(iter(self.values())) == 1
Expand Down
14 changes: 14 additions & 0 deletions pulp/tests/test_pulp.py
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,20 @@ def test_constraint_items_keys_values(self):
self.assertEqual(key_names, ["x", "y"])
self.assertEqual(sorted(c.values()), [2.0, 3.0])

def test_expression_get_missing_variable(self):
prob = self._make_prob()
x = prob.add_variable("x", 0, 10)
y = prob.add_variable("y", 0, 10)
expr = 2 * x + 1
self.assertEqual(expr.get(x), 2.0)
self.assertEqual(expr.get(x, 5.0), 2.0)
self.assertIsNone(expr.get(y))
self.assertEqual(expr.get(y, 5.0), 5.0)
prob += expr <= 10, "c1"
c = _constraint_named(prob, "c1")
self.assertIsNone(c.get(y))
self.assertEqual(c.get(y, 5.0), 5.0)

# -- 5. Auto-naming constraints --

def test_auto_named_constraint(self):
Expand Down
Loading