Sympy:如何解析诸如“2x”之类的表达式?

Rea*_*ess 5 sympy python-3.x

            #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)
Run Code Online (Sandbox Code Playgroud)

我试图制作一个使用 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
Run Code Online (Sandbox Code Playgroud)

Joh*_*anC 5

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)
Run Code Online (Sandbox Code Playgroud)

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

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