AILogicSolver / app.py
syeda-Rija20's picture
Update app.py
9b5bd69 verified
# import streamlit as st
# import sympy as sp
# import pandas as pd
# st.set_page_config(page_title="Logic Solver", layout="centered")
# st.title("🧩 AI Logic Solver")
# st.write("Enter a logical expression using:")
# st.write("~ (NOT), & (AND), | (OR), >> (IMPLIES)")
# # User input
# expr_input = st.text_input("Enter expression (e.g., ~(p & q) >> r):")
# if expr_input:
# try:
# # Define symbols
# p, q, r = sp.symbols('p q r')
# # Convert string to expression
# expr = sp.sympify(expr_input)
# st.subheader("πŸ“Œ Simplified Expression:")
# simplified = sp.simplify_logic(expr)
# st.write(simplified)
# # Truth table
# st.subheader("πŸ“Š Truth Table:")
# variables = sorted(expr.free_symbols, key=lambda x: str(x))
# rows = []
# for values in range(2**len(variables)):
# combination = list(map(int, bin(values)[2:].zfill(len(variables))))
# subs = dict(zip(variables, combination))
# result = expr.subs(subs)
# row = {str(var): val for var, val in subs.items()}
# row["Result"] = int(bool(result))
# rows.append(row)
# df = pd.DataFrame(rows)
# st.dataframe(df)
# except Exception as e:
# st.error("❌ Invalid expression. Please follow correct syntax.")
import streamlit as st
import sympy as sp
import pandas as pd
from sympy.logic.boolalg import Xor
# -----------------------
# Page Setup
# -----------------------
st.set_page_config(page_title="AI Logic Solver", layout="centered")
st.title("🧩 AI Logic Solver")
st.markdown("Solve logical expressions easily (with truth table)")
st.info("Use: ~ (NOT), & (AND), | (OR), >> (IMPLIES), ^ (XOR)")
# -----------------------
# Session State
# -----------------------
if "expr" not in st.session_state:
st.session_state.expr = ""
# -----------------------
# BUTTON FUNCTIONS
# -----------------------
def add(val):
st.session_state.expr += val
def clear():
st.session_state.expr = ""
def backspace():
st.session_state.expr = st.session_state.expr[:-1]
# -----------------------
# SIMPLE BUTTON UI
# -----------------------
st.subheader("πŸ”˜ Build Expression")
col1, col2, col3 = st.columns(3)
with col1:
if st.button("p"):
add("p")
if st.button("q"):
add("q")
if st.button("r"):
add("r")
with col2:
if st.button("AND (&)"):
add(" & ")
if st.button("OR (|)"):
add(" | ")
if st.button("NOT (~)"):
add("~")
with col3:
if st.button("IMPLIES (>>)"):
add(" >> ")
if st.button("XOR (^)"):
add(" ^ ")
if st.button("( )"):
add("()")
# Extra controls
col4, col5 = st.columns(2)
with col4:
if st.button("β¬… Backspace"):
backspace()
with col5:
if st.button("πŸ—‘ Clear"):
clear()
# -----------------------
# INPUT BOX
# -----------------------
expr_input = st.text_input("✏️ Your Expression:", value=st.session_state.expr)
# -----------------------
# PROCESSING
# -----------------------
if expr_input:
try:
# Clean input
expr_clean = expr_input.strip()
# Check parentheses
if expr_clean.count("(") != expr_clean.count(")"):
st.warning("⚠️ Unbalanced parentheses!")
# Replace XOR
expr_clean = expr_clean.replace("^", "Xor")
# Define symbols
p, q, r = sp.symbols('p q r')
# Parse expression
expr = sp.sympify(expr_clean, locals={"Xor": Xor})
st.success("βœ… Expression is valid!")
# -----------------------
# SIMPLIFY
# -----------------------
simplified = sp.simplify_logic(expr)
st.subheader("πŸ“Œ Simplified Expression:")
st.write(simplified)
# -----------------------
# TRUTH TABLE
# -----------------------
st.subheader("πŸ“Š Truth Table")
variables = sorted(expr.free_symbols, key=lambda x: str(x))
rows = []
for values in range(2**len(variables)):
combo = list(map(int, bin(values)[2:].zfill(len(variables))))
subs = dict(zip(variables, combo))
result = bool(expr.subs(subs)) # stable
row = {str(var): val for var, val in subs.items()}
row["Result"] = int(result)
rows.append(row)
df = pd.DataFrame(rows)
st.dataframe(df, use_container_width=True)
# Download option
st.download_button(
"πŸ“₯ Download CSV",
df.to_csv(index=False),
file_name="truth_table.csv",
mime="text/csv"
)
except Exception as e:
st.error("❌ Invalid expression!")
st.write("πŸ” Error detail:")
st.code(str(e))
st.info("πŸ’‘ Try examples:")
st.code("~(p & q) >> r")
st.code("p | q")
st.code("p ^ q")
st.code("(p & q) | (r)")