Untitled

Anonymous
plain_text
03/30/2026 10:20 AM
2.8 KB
10
Indexable
import sympy as sp

def solve_math(problem):
    try:
            # This parses the string into a math expression
                    expression = sp.simplify(problem)
                            
                                    # Check if it's an equation (has an '=') or just an expression
                                            if "=" in problem:
                                                        left, right = problem.split('=')
                                                                    equation = sp.Eq(sp.simplify(left), sp.simplify(right))
                                                                                result = sp.solve(equation)
                                                                                        else:
                                                                                                    result = expression.evalf() # Evaluates to a decimal
                                                                                                                
                                                                                                                        return result
                                                                                                                            except Exception as e:
                                                                                                                                    return f"Could not solve: {e}"

                                                                                                                                    # Test it out
                                                                                                                                    print(f"Result 1: {solve_math('2 + 2 * 5')}")
                                                                                                                                    print(f"Result 2: {solve_math('x**2 - 4 = 0')}")
                                                                                                                                    
Editor is loading...
Leave a Comment