Book Image

IPython Interactive Computing and Visualization Cookbook

By : Cyrille Rossant
Book Image

IPython Interactive Computing and Visualization Cookbook

By: Cyrille Rossant

Overview of this book

Table of Contents (22 chapters)
IPython Interactive Computing and Visualization Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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...

  1. Let's import SymPy:

    In [1]: from sympy import *
            init_printing()
  2. Let's define a few symbols:

    In [2]: var('x y z')
  3. We can define propositional formulas with symbols and a few operators:

    In [3]: P = x & (y | ~z); P
    Out[3]: And(Or(Not(z), y), x) 
  4. We can use subs() to evaluate a formula on actual Boolean values:

    In [4]: P.subs({x: True, y: False, z: True})
    Out[4]: False
  5. Now, we want to find a propositional formula depending...