gpt4 book ai didi

python - 简单表达式解析会抛出引用 'AssumptionKeys' 的 TypeError

转载 作者:行者123 更新时间:2023-12-02 15:44:24 25 4
gpt4 key购买 nike

我试图让 sympy 计算出应该是具有三个替换的简单表达式的结果,但我遇到了以前从未遇到过的错误。

>>> from sympy import sympify, symbols 
>>> input_str = '100*Q+10*R+5*S+0.6*T'
>>> Q,R,S,T = symbols('Q R S T')

上面的代码工作正常,但是当我通过 sympify 运行字符串时,出现以下错误:

>>> sympify(input_str)
ValueError: Error from parse_expr with transformed code: "Integer (100 )*Q +Integer (10 )*Symbol ('R' )+Integer (5 )*S +Float ('0.6' )*Symbol ('T' )"


The above exception was the direct cause of the following exception:

Traceback (most recent call last):

File "...ipykernel_5652\212826607.py", line 1, in <cell line: 1>
sympify(input_str)

File "...\Python\Python310\site-packages\sympy\core\sympify.py", line 496, in sympify
expr = parse_expr(a, local_dict=locals, transformations=transformations, evaluate=evaluate)

File "...\Python\Python310\site-packages\sympy\parsing\sympy_parser.py", line 1101, in parse_expr
raise e from ValueError(f"Error from parse_expr with transformed code: {code!r}")

File "...\Python\Python310\site-packages\sympy\parsing\sympy_parser.py", line 1092, in parse_expr
rv = eval_expr(code, local_dict, global_dict)

File "...Python\Python310\site-packages\sympy\parsing\sympy_parser.py", line 907, in eval_expr
expr = eval(

File "<string>", line 1, in <module>

TypeError: unsupported operand type(s) for *: 'Integer' and 'AssumptionKeys'

究竟是什么导致了如此简单的表达式出现此错误?

最佳答案

Q 是 SymPy 中不是符号的单字母对象之一。在简化过程中,函数(和一些单字母对象)被解析为它们的 SymPy 定义。如果使用不当(如本例),它会引发错误,就像解析“cos + x”或“beta + alpha”会引发错误一样,后者是因为 beta 是一个需要 1 或 2 个参数的函数. (为了记录,所有此类单字母符号都在“QOSINE”中;任何其他字母都将 sympify 没有问题。)已为此打开一个问题 here .处理此问题的方法之一是按照 abc.py 文件中的建议,在简化期间将冲突符号作为 locals 传递:

The module also defines some special names to help detect which names clashwith the default SymPy namespace._clash1 defines all the single letter variables that clash withSymPy objects; _clash2 defines the multi-letter clashing symbols;and _clash is the union of both. These can be passed for localsduring sympification if one desires Symbols rather than the non-Symbolobjects for those names.

>>> from sympy import S
>>> from sympy.abc import _clash1, _clash2, _clash
>>> S("Q & C", locals=_clash1)
C & Q
>>> S('pi(x)', locals=_clash2)
pi(x)
>>> S('pi(C, Q)', locals=_clash)
pi(C, Q)

关于python - 简单表达式解析会抛出引用 'AssumptionKeys' 的 TypeError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74849588/

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