-
Notifications
You must be signed in to change notification settings - Fork 0
/
truth_table.py
executable file
·85 lines (74 loc) · 2.21 KB
/
truth_table.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#!/usr/bin/python
from itertools import product
from operations import *
class Assignment:
"""Assignment of n boolean variables"""
def __init__(self, args):
self.args = tuple(args)
def __str__(self):
string = ''
for i in self.args:
string += i and 'T' or 'F'
string += ' & '
return string
def __getitem__(self, index):
return self.args[index]
def convert_to_rpn(expr, variables):
"""Dijkstra's shunting-yard algorithm
http://en.wikipedia.org/wiki/Shunting-yard_algorithm
"""
output = []
op_stack = []
for token in expr:
if token in OPS:
while op_stack and OPS[op_stack[0]]['pri'] >= OPS[token]['pri']:
output.append(op_stack.pop(0))
op_stack.insert(0, token)
elif token == '(':
op_stack.insert(0, token)
elif token == ')':
while op_stack[0] != '(':
output.append(op_stack.pop(0))
op_stack.remove(0)
else:
variables.append(token)
output.append(token)
while op_stack:
output.append(op_stack.pop(0))
variables.sort()
return output
def evaluate_rpn(expr):
stack = []
for token in expr:
if token not in OPS:
stack.insert(0, token)
else:
args = []
for i in range(OPS[token]['argc']):
args.insert(0, stack.pop(0))
stack.insert(0, OPS[token]['func'](args))
return stack[0]
def evaluate_possibilities(expr, variables):
possibilities = (Assignment(i) for i in product([True, False], repeat=len(variables)))
indices = {}
for i,j in enumerate(variables):
indices[j] = i
for p in possibilities:
new_expr = []
for token in expr:
if token not in OPS:
new_expr.append(p[variables.index(token)])
else:
new_expr.append(token)
row = str(p) + (evaluate_rpn(new_expr) and 'T' or 'F')
print row + '\\\\'
if __name__ == '__main__':
expr = raw_input('Enter expression with each token separated by a space: ')
variables = []
expr_tokens = expr.split()
rpn_expr = convert_to_rpn(expr_tokens, variables)
print '\\begin{tabular}{' + 'c'.join(('|' for i in range(len(variables) + 2))) + '}'
print ' & '.join(variables) + ' & ' + expr + '\\\\\hline'
evaluate_possibilities(rpn_expr, variables)
print '\hline'
print '\end{tabular}'