Lines 46
latex (1)
##### Permissions
Owner: midorikid
Viewable by Everyone
Editable by All Siafoo Users
Know what you're getting – Unlike many sites, all our code is clearly licensed.

# LaTeX Truth Table Generator 1

 In Brief Given a set of functions this snippet generates LaTeX truth table for all possible inputs.... more
 Language Python
# 's
 1def tfSeq(size): 2    ''' Generates a list of the given size containing all combinations 3    of True and False.  Starts with all Trues and ends with all 4    Falses. 5    ''' 6 7    if size > 1:         8        for head in tfSeq(size-1): 9            yield head + [True]10            yield head + [False]11    else:12        yield [True]13        yield [False]1415def truthtable(vars, funcs):16    ''' 17    :vars: A list of variable names.  This will be output as LaTeX18           math labels.  1920           Example: ['p','q','r']21    22    :funcs: A list of label/function pairs.  The label is a LaTeX math23            representation of the function.  The function is a Python24            function that takes the same number of arguments as there25            are variables in vars.  2627            Example: [('p \and q',lambda p,q: p and q)]2829    Returns a string containing code suitable for inserting directly30    into a LaTeX document.31    '''3233    output = ''3435    lVars = str(len(vars))36    lFuncs = str(len(funcs))37    output += r'\begin{tabular}{*{'+lVars+r'}{c}|*{'+lFuncs+r'}{c}}'3839    labels = vars + [func[0] for func in funcs]40    output += '&'.join(['$'+label+'$' for label in labels]) + r'\\'41    output += '\n\\hline\n'4243    tfText = {True:'T', False:'F'}4445    for tf in tfSeq(len(vars)):46        values = [tfText[val] for val in tf] 47        values += ([tfText[func[1](*tf)] for func in funcs])48        output += '&'.join(values) + '\\\\\n'49        5051    output += r'\end{tabular}'5253    return output545556# Example use...57if __name__ == '__main__':58    print truthtable(['p','q'], [('p \lor q'      ,lambda p,q: p or q),59                                 ('\sim(p \lor q)',lambda p,q: not(p or q)),60                                 ])

Given a set of functions this snippet generates LaTeX truth table for all possible inputs.

I use it as part of a Cheetah template to automatically insert truth tables into my documents.

It should be straight forward enough to modify for your needs. You can change the string representations for True and False, for example. You may want to remove the dollar-signs if you don't want to use mathematical notation.