Ayrat
Ayrat

Reputation: 1259

How to get clauses of the DNF/CNF expression in sympy?

According to sympy docs on logic package, we can transform an arbitrary boolean expression into DNF/CNF form, using to_cnf/to_dnf or simplify_logic(expr, form='cnf'/'dnf').

But after that, how to get the clauses from the result?

We can try using the args field. BUT using it is very inconvenient. E.g., if you transform a simple expression like ~a into CNF/DNF, then you get ~a as the result, and then calling (~a).args returns (), which is not the clause sought! (of course, I can workaround with if checks, but that is ugly)

Upvotes: 2

Views: 1667

Answers (1)

Ayrat
Ayrat

Reputation: 1259

I could not find the native method in sympy, but I was wrong when wrote that using args is ugly. Here is the solution.

def clauses(expr) -> tuple:    # for DNFs only
    if not isinstance(expr, sympy.logic.boolalg.Or):
        return expr,
    return expr.args

Notre that the function returns (true,)/(false,) for true/false values. For CNFs, change to isinstance(expr, And).

Upvotes: 2

Related Questions