SymPy: 如何解析类似于 '2x' 的表达式?

6
            #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来解决代数问题的discord机器人,但是在实施过程中一直遇到错误。有人可以帮忙吗?

但是对于输入 10 = 2xparse_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

这里一定有一个关于 sympy 的陷阱。由于 Python 的限制,即使有一个符号 x2x 也是无效的,必须写成 2*x - hpaulj
1个回答

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)

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

文档中还描述了许多其他可能的转换。需要注意的是,当组合变换时,结果并不总是如所希望的那样。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接