bastikr / boolean.py

Implements boolean algebra in one module.
BSD 2-Clause "Simplified" License
76 stars 34 forks source link

only use AND, OR , NOT #83

Open shezankazi opened 5 years ago

shezankazi commented 5 years ago

Is there any possibility parse only AND, OR and NOT operators? For example I cannot parse a query C OR C++ because of the ++ in the string.

tomas789 commented 1 year ago

The built-in parser is somehow limited and is not intended to be a fully general parser. So following script will fail

import boolean

algebra = boolean.BooleanAlgebra()
TRUE, FALSE, NOT, AND, OR, symbol = algebra.definition()

formula = algebra.parse("C|C++")
print(formula)

Traceback:

Traceback (most recent call last):
  File "/Users/tomaskrejci/Developer/quine-mccluskey/test.py", line 9, in <module>
    formula = algebra.parse("C|C++")
              ^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/tomaskrejci/Developer/quine-mccluskey/boolean.py/boolean/boolean.py", line 252, in parse
    raise ParseError(
boolean.boolean.ParseError: Invalid operator sequence without symbols such as AND OR or OR OR for token: "+" at position: 4

I see two options to go about this.

First, you can create the formula directly using Python primitives. If you need parsing then you'll need to build your own parser that can build the tree for you.

Here is an example that will work:

import boolean

algebra = boolean.BooleanAlgebra()
TRUE, FALSE, NOT, AND, OR, symbol = algebra.definition()

formula = OR(symbol("C"), symbol("C++"))
print(formula)

The output is simply C|C++. Note that the formula cannot be parsed using algebra.parse for the reason discussed above.

Second, you can rename the variables to something that you can parse. For example C becomes x0 and C++ becomes x1. You can then work with those names and convert them back to your original names when you are finished.