Python can use the eval() method to take a string and run it. In this case we calculate the Truth Table for a binary equation with a and b:
Binary equations (using Python eval) |
Sample run
The following is a sample run:
Operator: a ^ b A B Z ----------------- 0 0 0 0 1 1 1 0 1 1 1 0
Code
The following is the Python code:
import sys operator = "a ^ b" if (len(sys.argv)>1): operator=sys.argv[1] def nor(p, q): return ~ (p | q) & 0x01 def nand(p, q): return ~(p & q) & 0x01 def replace(op): op = op.replace("xor","^") op = op.replace("and","&") op = op.replace("or","|") op = op.replace("not","~") return(op) operator = replace(operator) if ('c' in operator.lower()): print ("Operator:\t",operator) print ("A\tB\tC\tZ") print ("-------------------------") for a in range(0,2): for b in range(0,2): for c in range(0,2): print (f"{a}\t{b}\t{c}\t{eval(operator) & 0x01}") else: print ("Operator:\t",operator) print ("A\tB\tZ") print ("-------------------------") for a in range(0,2): for b in range(0,2): print (f"{a}\t{b}\t{eval(operator) & 0x01}")
AND (Z=A.B)
A B Z ----- 0 0 0 0 1 0 1 0 0 1 1 1
OR (Z=A+B)
A B Z ----- 0 0 0 0 1 1 1 0 1 1 1 1
NAND (Z=A.B)
A B Z ----- 0 0 1 0 1 1 1 0 1 1 1 0
NOR (Z=A+B)
A B Z ----- 0 0 1 0 1 0 1 0 0 1 1 0
X-OR (Z=A⊕B)
A B Z ----- 0 0 0 0 1 1 1 0 1 1 1 0
The electronic gates used are: