简体   繁体   English

Python中的文本到数学方程

[英]Text to Math equation in Python

I'm writing now a pet project in which I want to draw a plot in the terminal window.我现在正在写一个宠物项目,我想在终端窗口中绘制一个情节。 The idea is that user print an equation, like x = y + 1 , or 3 * x = y .这个想法是用户打印一个方程,如x = y + 13 * x = y The question is how can I transfer this string equation to an equation in Python.问题是如何将这个字符串方程转换为 Python 中的方程。

For instance: I have an array, for x values like:例如:我有一个数组,对于x值,例如:

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

And then I want to put it into the user's equation to get y values.然后我想把它放到用户的方程中得到y值。 or vise versa (vise versa, put y values to get x values)反之亦然(反之亦然,将y值放入x值)

Thought to create a lot of if conditions and use for loop to detect every character but it seems something like a sandbox.想创建很多 if 条件并使用 for 循环来检测每个字符,但它看起来像一个沙盒。 Is there a more elegant way?有没有更优雅的方式?

You can do it using sympy library.你可以使用 sympy 库来做到这一点。

      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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM