Skip to content

Commit fe8b42f

Browse files
committed
Add sort keyword argument to DualBase simplify()
This commit adds a "sort" keyword argument to the simplify() function of the DualBase class. This allows simplification of boolean algebra expressions to be completed correctly, but does not sort the final expression. This is needed for various applications where maintaining order matters. Signed-off-by: Steven Esser <[email protected]>
1 parent e984df4 commit fe8b42f

File tree

2 files changed

+14
-2
lines changed

2 files changed

+14
-2
lines changed

boolean/boolean.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1135,7 +1135,7 @@ def __contains__(self, expr):
11351135
if isinstance(expr, self.__class__):
11361136
return all(arg in self.args for arg in expr.args)
11371137

1138-
def simplify(self):
1138+
def simplify(self, sort=True):
11391139
"""
11401140
Return a new simplified expression in canonical form from this
11411141
expression.
@@ -1254,7 +1254,8 @@ def simplify(self):
12541254
return args[0]
12551255

12561256
# Commutativity: A & B = B & A, A | B = B | A
1257-
args.sort()
1257+
if sort:
1258+
args.sort()
12581259

12591260
# Create new (now canonical) expression.
12601261
expr = self.__class__(*args)

boolean/test_boolean.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -705,6 +705,17 @@ def test_simplify(self):
705705
# Elimination
706706
self.assertEqual(a, ((a & ~b) | (a & b)).simplify())
707707

708+
# Commutativity + Non-Commutativity
709+
sorted_expression = (b & b & a).simplify()
710+
unsorted_expression = (b & b & a).simplify(sort=False)
711+
self.assertEqual(sorted_expression, unsorted_expression)
712+
self.assertNotEqual(sorted_expression.pretty(), unsorted_expression.pretty())
713+
714+
sorted_expression = (b | b | a).simplify()
715+
unsorted_expression = (b | b | a).simplify(sort=False)
716+
self.assertEqual(sorted_expression, unsorted_expression)
717+
self.assertNotEqual(sorted_expression.pretty(), unsorted_expression.pretty())
718+
708719
expected = algebra1.parse('(a&b)|(b&c)|(a&c)')
709720
result = algebra1.parse('(~a&b&c) | (a&~b&c) | (a&b&~c) | (a&b&c)', simplify=True)
710721
self.assertEqual(expected, result)

0 commit comments

Comments
 (0)