Finding a Boolean propositional formula from a truth table
The logic module in SymPy lets us manipulate complex Boolean expressions, also known as propositional formulas.
This recipe will show an example where this module can be useful. Let's suppose that, in a program, we need to write a complex if
statement depending on three Boolean variables. We can think about each of the eight possible cases (true, true and false, and so on) and evaluate what the outcome should be. SymPy offers a function to generate a compact logic expression that satisfies our truth table.
How to do it...
- Let's import SymPy:
>>> from sympy import * init_printing()
- Let's define a few symbols:
>>> var('x y z')
- We can define propositional formulas with symbols and a few operators:
>>> P = x & (y | ~z) P
- We can use
subs()
to evaluate a formula on actual Boolean values:>>> P.subs({x: True, y: False, z: True})
- Now, we want to find a propositional formula depending...