Search code examples
pythonsympyboolean-logictruthtable

Truth tables in python?


I am working in Python, and I would like to manipulate data in the form of truth tables. I need to simplify tables, translate tables to boolean expressions, etc... I discovered sympy, but it doesn't seem to provide native support for truth tables. I also found some other utilities, such as pyeda, but before diving into one of them I would like to know if there is any commonly accepted standard package to do what I need.

Any ideas? Thanks in advance.


Solution

  • Generating truth tables from a boolean expression is not that difficult with sympy.

    In the program below, the boolean expression is used to generate the list of models that are satisfiable. Using a generator for all possible variable truth combinations, it lists the complete truth table.

    import itertools
    from sympy import *
    from sympy.logic import simplify_logic
    from sympy.logic.inference import satisfiable
    
    my_names = 'ABCD'
    A,B,C,D = symbols(','.join(my_names))
    e1 = Nor(Nor(A, B), Or(C, D))
    my_symbols = sorted(e1.atoms(Symbol), key=lambda x: x.name)
    print('Set of symbols used:', my_symbols)
    models = satisfiable(e1, all_models=True)
    sat_mods = []
    for m in models:
        sat_mods.append(dict(sorted(m.items(), key=lambda x: x[0].name)))
    truth_tab = []
    for c in itertools.product((True, False), repeat=len(my_symbols)):
        model = dict(zip(my_symbols, c))
        truth_tab.append((model, model in sat_mods))
    print(truth_tab)
    

    Output:

    # Set of symbols used: [A, B, C, D]
    # [({A: True, B: True, C: True, D: True}, False),
    #  ({A: True, B: True, C: True, D: False}, False),
    # ...