Lines 46
latex (1)
##### Permissions
Owner: midorikid
Viewable by Everyone
Editable by All Siafoo Users

# 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:
11 else:
12 yield [True]
13 yield [False]
14
15def truthtable(vars, funcs):
16 '''
17 :vars: A list of variable names. This will be output as LaTeX
18 math labels.
19
20 Example: ['p','q','r']
21
22 :funcs: A list of label/function pairs. The label is a LaTeX math
23 representation of the function. The function is a Python
24 function that takes the same number of arguments as there
25 are variables in vars.
26
27 Example: [('p \and q',lambda p,q: p and q)]
28
29 Returns a string containing code suitable for inserting directly
30 into a LaTeX document.
31 '''
32
33 output = ''
34
35 lVars = str(len(vars))
36 lFuncs = str(len(funcs))
37 output += r'\begin{tabular}{*{'+lVars+r'}{c}|*{'+lFuncs+r'}{c}}'
38
39 labels = vars + [func[0] for func in funcs]
40 output += '&'.join(['$'+label+'$' for label in labels]) + r'\\'
41 output += '\n\\hline\n'
42
43 tfText = {True:'T', False:'F'}
44
45 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
50
51 output += r'\end{tabular}'
52
53 return output
54
55
56# 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.