How to simplify set expressions with union, intersection, and negation, in python

Question:

Is there any in-built python library that can be used to generate simplified set expressions?

For examples, let’s say, we have a set expression (A∩B)U(A∩C). This can be simplified as A∩(BUC).

Similarly (A∩B)U(A∩!B) can be simplified as A.

I am looking to implement this logic in python. I found that sympy can be used to simplify algebraic expressions like x**2 + 2*x + 1 but I am not sure it handles set expressions.

Asked By: brokendreams

||

Answers:

Yes. Set expressions are equivalent to boolean expressions, and sympy can simplify those.

Your examples:

  • (A∩B)U(A∩C) is equivalent to (a & b) | (a & c),
  • (A∩B)U(A∩!B) is equivalent to (a & b) | (a & ~b),
from sympy import *
a, b, c = symbols('a, b, c')

expr = (a & b) | (a & c)
simplify_logic(expr)  # produces: a∧(b∨c)

expr = (a & b) | (a & ~b)
simplify_logic(expr)  # produces: a

Some other examples can be found here.

Answered By: Vladimir Fokow
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.