gpt4 book ai didi

python-3.x - Sympy:如何解析 '2x' 等表达式?

转载 作者:行者123 更新时间:2023-12-04 20:56:51 25 4
gpt4 key购买 nike

            #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

最佳答案

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)
documentation描述了许多其他可能的变换。应该小心,因为结果并不总是所希望的,尤其是在组合转换时。

关于python-3.x - Sympy:如何解析 '2x' 等表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59632620/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com