Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python - representing boolean expressions with lists

I'm trying to represent boolean expressions in sum of products form(SOP) in Python with only lists.

For example, I have boolean expression

ABC+DE(FG+IH)

I need to find a list equivalent of the expression above, so by reading the list or nested list and following certain rules to read the list, the program/programmer reading the list will be able to convert it back to the boolean expression.

One way I thought of doing this is constructing nested lists. Two rules to follow:

  1. elements in the same list are ANDed together
  2. lists are parallel to each other, therfore ORed together.

So for the example above, it will translate to:

[[A,B,C],[D,E,[[F,G],[I,H]]]]

But this set of rules conflicts itself in some cases. For example, given [[E,F],[D,C]], it can either mean EF+DC or EFDC, as [E,F] and [D,C] are in the same list so they should be anded, but lists are parallel so they should be ORed too.

I feel like I need to set some precedence between the 2 rules above, or add another rule to make it more clear.

Any thoughts or suggestions are welcome. Also it's not homework, just something for fun. Thanks in advance!!

like image 824
turtlesoup Avatar asked Dec 13 '22 00:12

turtlesoup


1 Answers

You could go the LISPy route and have the first item in each list be the operator. For example, the expression you gave

ABC+DE(FG+IH)

would become

['or', ['and', A, B, C], ['and', D, E, ['or', ['and', F, G], ['and', I, H]]]]

Which is pretty readable, considering. Cheers!

like image 200
Xavier Holt Avatar answered Dec 28 '22 23:12

Xavier Holt