python-3.x - 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
解决方案
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)
该文档描述了许多其他可能的转换。应该小心,因为结果并不总是所希望的,尤其是在组合转换时。
推荐阅读
- object-detection - 在同一 GPU 上训练的 2 个 TENSORFLOW 对象检测模型的性能差异
- video-capture - 从实时视频播放中实时捕获文本
- flutter - 列表视图未正确重建
- django - Django 可以连续处理两个相关的 post 请求吗?第一篇文章的输入将被保存并用于第二篇文章
- excel - 在 Azure Workbooks 条形图图例被隐藏
- python - 使用 selenium Python 自动点击元素
- android-tv - Android TV Leanback:如何在 Fragment 中自定义顶部按钮
- css - CSS:骨架与模板-有什么区别?
- mysql - 为什么我的存储过程在以下查询中返回 NULL?
- elasticsearch - 如何按提供值排序并仅在 Elasticsearch7 的嵌套数组中获取匹配的元素