Skip to content

Instantly share code, notes, and snippets.

@a-andreyev
Forked from pindia/gist:3836713
Last active October 18, 2016 15:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save a-andreyev/8b72ed4f7913da7b35313044185f6e11 to your computer and use it in GitHub Desktop.
Save a-andreyev/8b72ed4f7913da7b35313044185f6e11 to your computer and use it in GitHub Desktop.
Python truth table calculator
#!/usr/bin/python2
# based on: https://gist.github.com/pindia/3836713
from itertools import izip, product, tee
# Logic functions: take and return iterators of truth values
def AND(a, b):
for p, q in izip(a, b):
yield p and q
def OR(a, b):
for p, q in izip(a, b):
yield p or q
def XOR(a, b):
for p, q in izip(a, b):
yield not(p is q)
def NOT(a):
for p in a:
yield not p
def EQUIV(a, b):
for p, q in izip(a, b):
yield p is q
def IMPLIES(a, b):
for p, q in izip(a, b):
yield (not p) or q
def create(num=2):
''' Returns a list of all of the possible combinations of truth for the given number of variables.
ex. [(T, T), (T, F), (F, T), (F, F)] for two variables '''
return list(product([True, False], repeat=num))
def unpack(data):
''' Regroups the list returned by create() by variable, making it suitable for use in the logic functions.
ex. [(T, T, F, F), (T, F, T, F)] for two variables '''
return [[elem[i] for elem in lst] for i, lst in enumerate(tee(data, len(data[0])))]
def print_result(data, result):
''' Prints the combinations returned by create() and the results returned by the logic functions in a nice format. '''
n = len(data[0])
headers = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'[:n]
print headers + "|RESULT"
print '-' * len(headers) + '+------'
for row, result_cell in izip(data, result):
print ''.join({True: '1', False:'0'}[cell] for cell in row) + '|' + ' ' + {True: '1', False:'0'}[result_cell]
if __name__ == '__main__':
data = create(num=4)
A, B, C, D = unpack(data)
# ((a XOR b) OR (c AND d)) AND (a AND b) OR (NOT c)
result = OR(AND(OR(XOR(A,B),AND(C,D)),AND(A,B)),NOT(C))
print_result(data, result)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment