Home > Enterprise >  How could I solve the error of putting a string in the sympy set solver with an input?
How could I solve the error of putting a string in the sympy set solver with an input?

Time:11-16

So I'm trying to create this program where it takes an input (for example x 2=5) and sympy solves that equation. However since I believe that "=" sign will cause an error I tried to cut it out from the input but with this I'm finding my self inputting a string type in the simpy solver. Is there any solution to this?

import math
from sympy import *

class operations():

    def __init__(self):
        self.operation = input()


    def solution(self, *o):
        x, y, z = symbols("x y z")
        equals = self.operation.split("=",1)[1]
        equation = self.operation.split("=")[0]
        solution = solveset(Eq(equation, int(equals)), x)
        print(solution)


operations().solution()

CodePudding user response:

You can use sympify to convert a string to a symbolic expression, although you will have to remove the equal sign first. In the following code, first I split the string where the equal sign is found, then I convert the two resulting strings to symbolic expressions with sympify, finally I solve the equation.

def solution(self, *o):
    left, right = [sympify(t) for t in self.operation.split("=")]
    solution = solveset(left - right) # solve left - right = 0
    print(solution)
  • Related