pythonsympyset-theory

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


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.


Solution

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

    Your examples:

    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.