Created
March 27, 2017 13:10
-
-
Save MarcScott/cb973177f0539629ff2c3a566d05a080 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## Functions for each gate. | |
def NAND(A, B): | |
if A == False: | |
return True | |
elif B == False: | |
return True | |
else: | |
return False | |
def NOT(A): | |
return NAND(A, A) | |
def AND(A, B): | |
C = NAND(A, B) | |
return NAND(C, C) | |
def OR(A, B): | |
C = NAND(A, A) | |
D = NAND(B, B) | |
return NAND(C, D) | |
def NOR(A, B): | |
C = NAND(A, A) | |
D = NAND(B, B) | |
E = NAND(C, D) | |
return NOT(E) | |
def XOR(A, B): | |
C = NAND(A, B) | |
D = NAND(A, C) | |
E = NAND(B, C) | |
return NAND(D, E) | |
## Functions to neatly print out the gates as bools or ints | |
def print_table_bool(gate): | |
print('\n Truth table for', gate.__name__,'\n') | |
inputs = [(bool(A), bool(B)) for A in range(2) for B in range(2)] ## create boolean inputs | |
## Print the tables | |
print('| Input A | Input B | Output |') | |
print('|=========|=========|========|') | |
for i in inputs: | |
print('| {0: <8}| {1: <8}| {2: <7}|'.format(str(i[0]), str(i[1]), str(gate(i[0], i[1])))) | |
print('|----------------------------|') | |
def print_table_int(gate): | |
print('\n Truth table for', gate.__name__,'\n') | |
inputs = [(A, B) for A in range(2) for B in range(2)] ## create integer inputs | |
## Print the tables | |
print('| Input A | Input B | Output |') | |
print('|=========|=========|========|') | |
for i in inputs: | |
print('| {0: <8}| {1: <8}| {2: <7}|'.format(i[0], i[1], gate(i[0], i[1]))) | |
print('|----------------------------|') | |
## List of all the gates (except NOT gate) | |
gates = [NAND, AND, OR, NOR, XOR] | |
## Print out tables for all gates | |
for gate in gates: | |
print_table_bool(gate) | |
# |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment