Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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()

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading