Home > Back-end >  Text to Math equation in Python
Text to Math equation in Python

Time:06-22

I'm writing now a pet project in wich I want to draw a plot in terminal window. The idea is that user print an equation, like x = y 1, or 3*x = y. The question is how can I transfom this string equation to equation in Python.

For instance: I have an arraty, for x values like:

x_arr = [1, 2, 3, 4, 5]

And then I want to put it into the user's equation to get y values. or vise versa (vise versa, put y values to get x values)

Thought to create a lot of if conditions and use for loop to detect every characters but it seems smth like sandbox. Is there more elegant way?

CodePudding user response:

You can do it using sympy library.

      from sympy import *
      from sympy.solvers import solve
      x,y = symbols('x,y')
      eq = '3*x=y*2'
      parts = [x.strip() for x in eq.split('=')]
      final_eq = parts[1] '-({})'.format(parts[0])
      equation = Eq(eval(parts[0]),eval(parts[1]))
      x_array = [1,2,3,4,5]
      for x1 in x_array:
            print('given x={}, y={}'.format(x1,solve(equation.subs(x,x1),y)))

Ouput

      given x=1, y=[3/2]
      given x=2, y=[3]
      given x=3, y=[9/2]
      given x=4, y=[6]
      given x=5, y=[15/2]

CodePudding user response:

Use eval for evaluating the textual commands.

https://www.programiz.com/python-programming/methods/built-in/eval

  • Related