Repository navigation
Expand file tree
/
Copy pathLogic_Truth_Table_Generator.py
More file actions
234 lines (186 loc) · 7.7 KB
/
Copy pathLogic_Truth_Table_Generator.py
File metadata and controls
234 lines (186 loc) · 7.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
"""
import tkinter as tk
from itertools import product
#define basic logic gates
def AND(a,b):
return a&b
def OR(a,b):
return a|b
def NOT(a):
return 1-a
def XOR(a,b):
return a^b
def XNOR(a,b):
return 1-(a^b)
def POS_INHIB(a,b):
return a & (1-b)
def NEG_INHIB(a,b):
return (1-a) & b
#function to generate truthtable
def generate_table():
expr=entry_expr.get()
n= int(entry_vars.get())
variables=['A','B','C','D','E'][:n]
result_text.delete(1.0, tk.END)
result_text.insert(tk.END,f"Truth table for:{expr}\n")
result_text.insert(tk.END,"-"*40+ "\n")
result_text.insert(tk.END,"|".join(variables)+ "Output\n")
result_text.insert(tk.END,"-"*40+ "\n")
all_results = []
for combo in product([0,1], repeat=n):
local_vars = dict(zip(variables, combo))
#Replace gate names with python functions
expr_eval =expr.replace("AND","&").replace("OR","|").replace("NOT","1-").replace("XOR","^")
try:
#define local varialbes value
A,B,C,D,E =[local_vars.get(v,0) for v in ['A','B','C','D','E']]
result= eval(expr_eval)
all_results.append((combo,result))
result_text.insert(tk.END,"|".join(map(str,combo)) + f" | {result}\n")
except Exception as e:
result_text.insert(tk.END, f"Error evaluating for {combo}: {e}\n")
result_text.insert(tk.END, "-"*40+ "\n")
result_text.insert(tk.END, "Truth table generated successfully")
#GUI Setup
root =tk.Tk()
root.title("Logic circuit truthtable generator")
tk.Label(root, text="Enter logic expression").pack(pady=5)
entry_expr = tk.Entry(root, width=40)
entry_expr.pack()
tk.Label(root, text="Enter number of variables (1-5)").pack(pady=5)
entry_vars = tk.Entry(root, width=10)
entry_vars.pack()
tk.Button(root, text="Generate truth table", command=generate_table, bg="lightgreen").pack(pady=10)
result_text = tk.Text(root, height=15, width=60)
result_text.pack(padx=10, pady=10)
root.mainloop()
#advacned code with sympy
import tkinter as tk
from itertools import product
from sympy import symbols, sympify,And, Or,Not, Xor, Implies
#GUI
def generate_table():
expr_str= entry_expr.get().upper()
n= int(entry_vars.get())
variables = ['A','B','C','D','E'][:n]
result_text.delete(1.0,tk.END)
result_text.insert(tk.END,f"Truthtable for: {expr_str}\n")
result_text.insert(tk.END,"-"*45 +"\n")
result_text.insert(tk.END,"|".join(variables) + "|Output\n")
result_text.insert(tk.END,"-"*45 +"\n")
#create sympy symbols dynamically
sym_vars=symbols(variables)
#Replace user input with sympy-compatible syntax
expr_str= expr_str.replace("AND", "&")
expr_str = expr_str.replace("OR","|")
expr_str = expr_str.replace("NOT","~")
expr_str = expr_str.replace("XOR","^")
expr_str = expr_str.replace("XNOR","~(") +")" if "XNOR" in expr_str else expr_str
expr_str = expr_str.replace("NAND", "~(") + ")" if "NAND" in expr_str else expr_str
expr_str = expr_str.replace("NOR", "~(") + ")" if "NOR" in expr_str else expr_str
expr_str = expr_str.replace("IMP", "Implies")
expr_str = expr_str.replace("INHIB", "And(").replace("NOT", "NOT(")
try:
expr = sympify(expr_str)
except Exception as e:
result_text.insert(tk.END, f"Error parsing expression: {e}\n")
return
#generate truthtable
for combo in product([0,1], repeat=n):
values= dict(zip(sym_vars, combo)) #ask how this code is different then previous one
try:
result = int(expr.subs(values))
except Exception:
result = "Err"
result_text.insert(tk.END, "|".join(map(str,combo)) + f" | {result}\n")
result_text.insert(tk.END, "-"*45 + "\n")
result_text.insert(tk.END, "Truth table generated successfully")
#gui #what if the gui code lines are intended one block ahead?
root = tk.Tk()
root.title("Logic circuit truthtable (sympy version)")
root.geometry("600x500")
tk.Label(root, text="Enter logic expression", font=("Arial",10)).pack(pady=5)
entry_expr = tk.Entry(root,width=50)
entry_expr.pack(pady=3)
tk.Label(root, text="Enter number of variables (1-5)", font=("Arial",10)).pack(pady=5)
entry_vars = tk.Entry(root,width=10)
entry_vars.pack(pady=3)
tk.Button(root, text="Generate Truth table", bg="lightgreen", font=("Arial", 10,"bold"), command=generate_table).pack(pady=10) #earlier it was tk.Button(root, height=18, width =70, font=("Courier, 10")) , no output came
result_text = tk.Text(root, height=18, width=70, font=("Courier,10"))
result_text.pack(padx=10,pady=10)
root.mainloop()
error coming in this code:
"""
import tkinter as tk
import re
from itertools import product
from sympy import symbols, sympify
import csv
from datetime import datetime
# --------- Preprocess user input for SymPy ----------
def preprocess(expr):
e = expr.upper()
e = re.sub(r'\b([A-E])\s+NAND\s+([A-E])\b', r'~(\1 & \2)', e)
e = re.sub(r'\b([A-E])\s+NOR\s+([A-E])\b', r'~(\1 | \2)', e)
e = re.sub(r'\b([A-E])\s+XNOR\s+([A-E])\b', r'~(\1 ^ \2)', e)
e = re.sub(r'\b([A-E])\s+IMP\s+([A-E])\b', r'(~\1) | \2', e)
e = re.sub(r'\b([A-E])\s+INHIB\s+([A-E])\b', r'(\1 & ~\2)', e)
e = e.replace("AND", "&").replace("OR", "|").replace("NOT", "~").replace("XOR", "^")
e = re.sub(r'\s+', ' ', e).strip()
return e
# --------- Generate truth table ----------
def generate_table():
raw_expr = entry_expr.get().strip()
try:
n = int(entry_vars.get().strip())
if not (1 <= n <= 5):
raise ValueError("Enter 1–5")
except Exception as ex:
result_text.delete(1.0, tk.END)
result_text.insert(tk.END, f"Invalid number of variables: {ex}\n")
return
sym_vars = symbols('A B C D E')[:n]
var_names = [str(v) for v in sym_vars]
expr_text = preprocess(raw_expr)
result_text.delete(1.0, tk.END)
result_text.insert(tk.END, f"Expression (preprocessed): {expr_text}\n")
result_text.insert(tk.END, "-" * (6 * n + 20) + "\n")
result_text.insert(tk.END, " | ".join(var_names) + " | OUTPUT\n")
result_text.insert(tk.END, "-" * (6 * n + 20) + "\n")
try:
expr = sympify(expr_text)
except Exception as e:
result_text.insert(tk.END, f"Error parsing expression: {e}\n")
return
all_results = [] # store rows for CSV
for combo in product([0, 1], repeat=n):
subs_map = {sym_vars[i]: bool(combo[i]) for i in range(n)}
try:
val = expr.subs(subs_map)
out = int(bool(val))
except Exception:
out = "Err"
all_results.append(list(combo) + [out])
result_text.insert(tk.END, " | ".join(map(str, combo)) + f" | {out}\n")
# Save to CSV
filename = f"truth_table_{datetime.now().strftime('%Y%m%d_%H%M%S')}.csv"
with open(filename, mode='w', newline='') as f:
writer = csv.writer(f)
writer.writerow(var_names + ["Output"])
writer.writerows(all_results)
result_text.insert(tk.END, "-" * (6 * n + 20) + "\n")
result_text.insert(tk.END, f"✅ Truth table generated and saved as {filename}\n")
# ---------- GUI Setup ----------
root = tk.Tk()
root.title("Logic Truth Table (SymPy + CSV)")
root.geometry("620x520")
tk.Label(root, text="Enter logic expression (e.g. (A AND B) OR (NOT C))").pack(pady=6)
entry_expr = tk.Entry(root, width=60)
entry_expr.pack(pady=2)
tk.Label(root, text="Number of variables (1–5)").pack(pady=6)
entry_vars = tk.Entry(root, width=8)
entry_vars.pack(pady=2)
tk.Button(root, text="Generate Truth Table", command=generate_table, bg="#8fbc8f").pack(pady=10)
result_text = tk.Text(root, width=80, height=20, font=("Consolas", 10))
result_text.pack(padx=10, pady=8)
root.mainloop()