1

I need to compare a given logical expression with another in java, to identify if both are the same. For example, consider an expression as ((a&b)&(c|d)&(e&f)) and other as ((a&e)&(c|d)&(b&f)), they both are equivalent. Consider (a&(f&(b&e))&(c|d)): this is also equivalent. Furthermore, this expressions can be nested. I thought of converting this to prefix notations, but can't find a proper way through. Expressions is a recursive class object with expression-type as AND/OR and an array of it's child expressions ex. for above first expression:

{
    type: AND,
    expressions: [{
        type: AND,
        expressions: [{
            type: SIMPLE,
            expression: [a]       <-- this could also be nested if type would have been logical
        }, {
            type: SIMPLE,
            expression: [b]
        }]
    }, {
        type: OR,
        expressions: [{
            type: SIMPLE,
            expression: [c]
        }, {
            type: SIMPLE,
            expression: [d]
        }]
    }, {
        type: AND,
        expressions: [{
            type: SIMPLE,
            expression: [e]
        }, {
            type: SIMPLE,
            expression: [f]
        }]
    }]
}

Is there any way to simplify expressions and compare them?

4

1 回答 1

1

您可以使用“boolean.py”模块来执行此操作。如果你想尝试一下,有一点技巧。您需要通过“pip install boolean.py”与“pip install boolean”进行安装。它们是两个不同的包,你想要 '.py' 版本。

以下是您的示例,以及我添加的失败案例:

import boolean
algebra = boolean.BooleanAlgebra()
expr1 = algebra.parse("((a&b)&(c|d)&(e&f))").simplify()
expr2 = algebra.parse("((a&e)&(c|d)&(b&f))").simplify()
expr3 = algebra.parse("(a&(f&(b&e))&(c|d))").simplify()
print(expr1 == expr2)
print(expr1 == expr3)

expr4 = algebra.parse("(a&(f&(b&e))&(c|d)&(x|y))").simplify()
expr5 = algebra.parse("(a&(f&(b&e))&(c|y)&(x|d))").simplify()

print(expr4 == expr5)

结果:

True
True
False
于 2020-10-17T21:39:46.820 回答