The following function creates a 3 bit adder truth table. How can I get an 2D array structure from the output?
import numpy as np
def truthTable(inputs=3):
if inputs == 3:
print(" A B C S Cout ")
for a in range(0, 2):
for b in range(0, 2):
for c in range(0, 2):
cout = eval("((a & b) | (a & c) | (b & c))")
s = eval("(a ^ b ^ c)")
print(str(a) "," str(b) "," str(c) "," str(s) "," str(cout))
truthTable()
couurent o/p:
0,0,0,0,0
0,0,1,1,0
0,1,0,1,0
0,1,1,0,1
1,0,0,1,0
1,0,1,0,1
1,1,0,0,1
1,1,1,1,1
CodePudding user response:
import numpy as np
def truthTable(inputs=3):
if inputs == 3:
print(" A B C S Cout ")
tt = []
for a in range(0, 2):
for b in range(0, 2):
for c in range(0, 2):
cout = eval("((a & b) | (a & c) | (b & c))")
s = eval("(a ^ b ^ c)")
tt.append([a, b, c, s, cout])
return tt
print(truthTable())
[[0, 0, 0, 0, 0], [0, 0, 1, 1, 0], [0, 1, 0, 1, 0], [0, 1, 1, 0, 1], [1, 0, 0, 1, 0], [1, 0, 1, 0, 1], [1, 1, 0, 0, 1], [1, 1, 1, 1, 1]]
CodePudding user response:
import numpy as np
import itertools
def get_cout(a,b,c):
return eval("((a & b) | (a & c) | (b & c))")
def get_s(a,b,c):
return eval("(a ^ b ^ c)")
all_booleans = list(itertools.product([0, 1], repeat=3))
for i in all_booleans:
print(f"{str(i[0])},{str(i[1])},{str(i[2])},{str(get_s(i[0],i[1],i[2]))},{str(get_cout(i[0],i[1],i[2]))}")
Output:
0,0,0,0,0
0,0,1,1,0
0,1,0,1,0
0,1,1,0,1
1,0,0,1,0
1,0,1,0,1
1,1,0,0,1
1,1,1,1,1