Skip to content

Instantly share code, notes, and snippets.

@yvbbrjdr
Last active February 14, 2019 00:42
Show Gist options
  • Select an option

  • Save yvbbrjdr/b031258e5a7e4bb4308c4bce41150260 to your computer and use it in GitHub Desktop.

Select an option

Save yvbbrjdr/b031258e5a7e4bb4308c4bce41150260 to your computer and use it in GitHub Desktop.
A truth table (CSV) generator for your logic class!
"""
A truth table (CSV) generator for your logic class!
Example:
$ python truth_table.py
Variables: p; q
Formulae: p and q; p or q; not p; implies(p, q); p == q
"p","q","p and q","p or q","not p","implies(p, q)","p == q"
True,True,True,True,False,True,True
True,False,False,True,False,False,False
False,True,False,True,True,True,False
False,False,False,False,True,True,True
"""
import readline
import sys
def main(argc, argv):
out_file = sys.stdout
if argc > 1:
out_file = open(argv[1], 'w')
nvariables, variables = input_list('Variables')
nformulae, formulae = input_list('Formulae')
print(','.join('"{}"'.format(s) for s in variables + formulae), file=out_file)
frame = {'implies': lambda x, y: not x or y}
for i in range(2 ** nvariables):
tmp = []
for j in range(nvariables):
value = i & 1 == 0
i >>= 1
frame[variables[nvariables - j - 1]] = value
tmp.append(value)
tmp = list(reversed(tmp))
tmp.extend(eval(formula, frame) for formula in formulae)
print(','.join(str(s) for s in tmp), file=out_file)
out_file.close()
def input_list(prompt):
ret = list(filter(None, (s.strip() for s in input(prompt + ': ').split(';'))))
return len(ret), ret
if __name__ == '__main__':
main(len(sys.argv), sys.argv)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment