CoolFace
Apppublic

SaraQamarSultan/Math_Problem_Solver

sourceHugging Faceupdated 2y agoView on Hugging Face
0likes
app.py61 linesDownload Raw Back to root
1import streamlit as st2import sympy as sp3import re4 5# Streamlit page setup6st.title("Math Problem Solver")7st.write("Enter a math problem (e.g., equation, derivative, integral) to solve it.")8 9# Input the math problem as a string10math_input = st.text_area("Enter your math problem here", "")11 12# Function to preprocess the input and add missing multiplication signs13def preprocess_input(problem):14    # Add '*' between numbers and variables15    problem = re.sub(r'(\d)([a-zA-Z])', r'\1*\2', problem)16    return problem17 18# Function to solve the math problem19def solve_math_problem(problem):20    try:21        # Preprocess input to handle implicit multiplication22        problem = preprocess_input(problem)23 24        # Check if the problem contains an equation (i.e., '=' symbol)25        if '=' in problem:26            # Split the problem into left-hand side and right-hand side27            lhs, rhs = problem.split('=')28            lhs_expr = sp.sympify(lhs)29            rhs_expr = sp.sympify(rhs)30            equation = sp.Eq(lhs_expr, rhs_expr)  # Create an equation for solving31            solution = sp.solve(equation)32            return f"Solution: {solution}"33        34        # Parse the input string into a SymPy expression for other cases35        expr = sp.sympify(problem)36        37        # If the expression is a derivative, compute the derivative38        if 'derivative' in problem.lower():39            var = sp.symbols('x')  # Assuming derivative with respect to 'x'40            derivative = sp.diff(expr, var)41            return f"Derivative: {derivative}"42 43        # If the expression is an integral, compute the integral44        if 'integral' in problem.lower():45            var = sp.symbols('x')  # Assuming integral with respect to 'x'46            integral = sp.integrate(expr, var)47            return f"Integral: {integral}"48 49        # General simplification for algebraic expressions50        simplified_expr = sp.simplify(expr)51        return f"Simplified Expression: {simplified_expr}"52 53    except Exception as e:54        return f"Error: {e}"55 56# Solve the math problem if there is an input57if math_input:58    result = solve_math_problem(math_input)59    st.subheader("Result")60    st.write(result)61