This is one of the 100 recipes of the IPython Cookbook, the definitive guide to high-performance scientific computing and data science in Python.
from sympy import *
init_printing()
Let's define a few variables.
var('x y z')
We can define propositional formulas with symbols and a few operators.
P = x & (y | ~z); P
P.subs({x: True, y: False, z: True})
Now, we want to find a propositional formula depending on x, y, z, with the following truth table:
%%HTML
<style>
table.truth_table tr {
margin: 0;
padding: 0;
}
table.truth_table td, table.truth_table th {
width: 30px;
text-align: center;
margin: 0;
padding: 0;
}
</style>
<table class="truth_table">
<tr>
<th>x</th><th>y</th><th>z</th><th>??</th>
</tr>
<tr>
<td>T</td><td>T</td><td>T</td><th>*</th>
</tr>
<tr>
<td>T</td><td>T</td><td>F</td><th>*</th>
</tr>
<tr>
<td>T</td><td>F</td><td>T</td><th>T</th>
</tr>
<tr>
<td>T</td><td>F</td><td>F</td><th>T</th>
</tr>
<tr>
<td>F</td><td>T</td><td>T</td><th>F</th>
</tr>
<tr>
<td>F</td><td>T</td><td>F</td><th>F</th>
</tr>
<tr>
<td>F</td><td>F</td><td>T</td><th>F</th>
</tr>
<tr>
<td>F</td><td>F</td><td>F</td><th>T</th>
</tr>
</table>
x | y | z | ?? |
---|---|---|---|
T | T | T | * |
T | T | F | * |
T | F | T | T |
T | F | F | T |
F | T | T | F |
F | T | F | F |
F | F | T | F |
F | F | F | T |
Let's write down all combinations that we want to evaluate to True, and those for which the outcome does not matter.
minterms = [[1,0,1], [1,0,0], [0,0,0]]
dontcare = [[1,1,1], [1,1,0]]
Now, we use the SOPform function to derive an adequate proposition.
Q = SOPform(['x', 'y', 'z'], minterms, dontcare); Q
Let's test that this proposition works.
Q.subs({x: True, y: False, z: False}), Q.subs({x: False, y: True, z: True})
You'll find all the explanations, figures, references, and much more in the book (to be released later this summer).
IPython Cookbook, by Cyrille Rossant, Packt Publishing, 2014 (500 pages).