Home > database >  Python Sympy - Check if a variable is present in the monomials of the ANF of a Boolean expression
Python Sympy - Check if a variable is present in the monomials of the ANF of a Boolean expression

Time:02-02

I have a Boolean expression that is transformed to its Algebraic Normal Form (ANF), with the logic module of Sympy. Find below a dummy example with six variables.

from sympy import symbols
from sympy.logic.boolalg import to_anf

a = symbols('a:{}'.format(2))
b = symbols('b:{}'.format(3))
c = symbols('c:{}'.format(1))

expr = ((a[0] & (~b[0])) ^ b[1]) & ((a[1] & (~b[2])) ^ c[0])
anf  = expr.to_anf()

which prints

(a0 & a1) ^ (a0 & c0) ^ (a1 & b1) ^ (b1 & c0) ^ (a0 & a1 & b0) ^ (a0 & a1 & b2) ^ (a0 & b0 & c0) ^ (a1 & b1 & b2) ^ (a0 & a1 & b0 & b2)

I would like to find which monomials of the resulting ANF have the variable c0.

CodePudding user response:

If you are looking for a certain type of subexpression, using atoms can be a good way to go:

# after your code
>>> from sympy import And
>>> [i for i in anf.atoms(And) if i.has(c[0])]
[b1 & c0, a0 & b0 & c0, a0 & c0]

CodePudding user response:

The solution is

  1. to first split the monomials of the ANF,
monomials = [monom for monom in anf.args if anf.args]
  1. then check if the variable is present in each monomial.
[monom for monom in monomials if c[0] in monom.args]

Output:

[a0 & c0, b1 & c0, a0 & b0 & c0]
  • Related