Skip to content

Commit d061cd4

Browse files
authored
this was fun to make :D
1 parent 046bf1b commit d061cd4

1 file changed

Lines changed: 39 additions & 0 deletions

File tree

system/LogicGates.py

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
from itertools import product
2+
import time
3+
4+
def truth_table(num_vars, func, gate_name):
5+
if num_vars != func.__code__.co_argcount:
6+
raise ValueError(f"{gate_name} expects {func.__code__.co_argcount} inputs")
7+
8+
vars_names = [chr(ord('A') + i) for i in range(num_vars)]
9+
header = " | ".join(vars_names) + " | OUT"
10+
print(f"\n=== {gate_name} ===")
11+
print(header)
12+
print("-" * len(header))
13+
14+
for inputs in product([0, 1], repeat=num_vars):
15+
out = func(*inputs)
16+
row = " | ".join(str(x) for x in inputs)
17+
print(f"{row} | {out}")
18+
19+
def AND(A, B): return int(A and B)
20+
def OR(A, B): return int(A or B)
21+
def NOT(A): return int(1 - A)
22+
def NAND(A, B): return int(not (A and B))
23+
def NOR(A, B): return int(not (A or B))
24+
def XOR(A, B): return int(A ^ B)
25+
def XNOR(A, B): return int(not (A ^ B))
26+
27+
gates = {"AND": (2, AND), "OR": (2, OR), "NOT": (1, NOT), "NAND": (2, NAND), "NOR": (2, NOR), "XOR": (2, XOR), "XNOR": (2, XNOR)}
28+
gate_items = list(gates.items())
29+
for i, (name, (num_vars, func)) in enumerate(gate_items):
30+
truth_table(num_vars, func, name)
31+
32+
if i < len(gate_items) - 1:
33+
input("\nPlease press `Enter` to continue")
34+
print("---------------------------------")
35+
print("Please wait loading next table...")
36+
time.sleep(4) # Time sleep (so wait 4 seconds)
37+
else: # Added else statement after the XNOR gate
38+
print("---------------------------------")
39+
print("End of LogicGate Demo!")

0 commit comments

Comments
 (0)