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

Time:08-17

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.

CodePudding user response:

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.

  • Related