首页 > 解决方案 > Sympy:如何解析“2x”等表达式?

问题描述

            #split the equation into 2 parts using the = sign as the divider, parse, and turn into an equation sympy can understand
            equation = Eq(parse_expr(<input string>.split("=")[0]), parse_expr(<input string>.split("=")[1]))
            answers = solve(equation)
            #check for answers and send them if there are any
            if answers.len == 0:
                response = "There are no solutions!"
            else:
                response = "The answers are "
                for answer in answers:
                    response = response + answer + ", "
                response = response[:-2]
        await self.client.send(response, message.channel)

我试图制作一个使用 sympy 解决代数问题的不和谐机器人,但我在上面的实现中一直遇到错误。有人可以帮忙吗?

但是对于输入10 = 2x parse_expr给出了语法错误。我怎样才能使用parse_expr或一些类似的功能来接受这种表达方式?

错误:

  File "C:\Users\RealAwesomeness\Documents\Github\amber\amber\plugins/algebra.py", line 19, in respond
    equation = Eq(parse_expr(c[2].split("=")[0]),parse_expr(c[2].split("=")[1]))
  File "C:\Users\RealAwesomeness\AppData\Local\Programs\Python\Python38-32\lib\site-packages\sympy\parsing\sympy_parser.py", line 1008, in parse_expr
    return eval_expr(code, local_dict, global_dict)
  File "C:\Users\RealAwesomeness\AppData\Local\Programs\Python\Python38-32\lib\site-packages\sympy\parsing\sympy_parser.py", line 902, in eval_expr
    expr = eval(
  File "<string>", line 1
    Integer (2 )Symbol ('x' )
                ^
SyntaxError: invalid syntax

标签: python-3.xsympy

解决方案


parse_expr允许通过其transformations=参数灵活输入。

其中implicit_multiplication_application允许省略*可以假定乘法的时间。很多时候,人们也想^要求幂,而 Python 标准使用**求幂,并为异或保留^。转换convert_xor负责该转换。

这是一个例子:

from sympy.parsing.sympy_parser import parse_expr, standard_transformations, implicit_multiplication_application, convert_xor

transformations = (standard_transformations + (implicit_multiplication_application,) + (convert_xor,))

expr = parse_expr("10tan x^2 + 3xyz + cos theta",
                  transformations=transformations)

结果:3*x*y*z + cos(theta) + 10*tan(x**2)

文档描述了许多其他可能的转换。应该小心,因为结果并不总是所希望的,尤其是在组合转换时。


推荐阅读