Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to determine whether or not two symbolic boolean expressions are equal in Python?

I've been trying to determine boolean expression equivalence with Sympy, but it seems it doesn't detect equivalence of more complex expressions

from sympy.abc import x, y
from sympy.logic.boolalg import *

print(Equivalent(x, x))
print(Equivalent(x, x & True))
print(Equivalent(x | y, y | x))
print(Equivalent(x | (x & y), x | y))
print(Equivalent(~x & ~y, ~(x | y)))

Results:

>>>True
>>>True
>>>True
>>>Equivalent(Or(x, y), Or(And(x, y), x))
>>>Equivalent(Not(Or(x, y)), And(Not(x), Not(y)))

Is there a way to determine whether or not two symbolic boolean expressions are equal in Python?

like image 400
electricman Avatar asked Dec 16 '17 22:12

electricman


2 Answers

equals works fine for me:

( x|(x&y) ).equals( x|y )
# False

( ~x&~y ).equals( ~(x|y) )
# True

In general, equals tries to transform the two expressions until they are equal to each other and only returns False if it fails. It is therefore more accurate (but also slower) than ==.

like image 155
Wrzlprmft Avatar answered Oct 02 '22 14:10

Wrzlprmft


sympy.simplify_logic perhaps?

>>> sympy.simplify_logic(Equivalent(Or(x, y), Or(And(x, y), x)))
Or(Not(y), x)
>>> sympy.simplify_logic(Equivalent(Not(Or(x, y)), And(Not(x), Not(y))))
True
like image 29
Tadhg McDonald-Jensen Avatar answered Oct 02 '22 16:10

Tadhg McDonald-Jensen