是否可以取消保留SymPy中的保留字母,例如sympy.E并使其成为sympy.Symbol?
Is it possible to unreserve the reserved letters in SymPy Such as sympy.E and make it a sympy.Symbol?
假设出于某种原因您需要或更喜欢将 E 或 SymPy 的任何其他保留字母作为符号。所以当你问 sympy.sympify("E") 时,你想要 <class 'sympy.core.symbol.Symbol'>
而不是 <class 'sympy.core.numbers.Exp1'>
。一个简单的小例子看下面的代码。
import sympy
symbols_list = sympy.symbols(' '.join(["A","E","Y"]))
expr = sympy.sympify("Y + 2 * E")
print(f"variables in expr are {expr.free_symbols}")
for x in symbols_list:
print(f"coefficient of {x} in expr is {expr.coeff(x)}")
那么打印出来的信息就是
variables in expr are {Y}
coefficient of A in expr is 0
coefficient of E in expr is 0
coefficient of Y in expr is 1
趁我想看的时候
variables in expr are {Y, E}
coefficient of A in expr is 0
coefficient of E in expr is 2
coefficient of Y in expr is 1
有没有办法强制 SymPy 在脚本开头声明一些东西以忘记它在这个脚本中的 E?
您应该直接使用 parse_expr
而不是 sympify
来自定义解析器的行为。使用 parse_expr
,您可以指定在执行解析代码时要使用的 local_dict
和 global_dict
。在这种情况下,它是定义 E
的 global_dict
,但您可以使用 local_dict
:
覆盖它
In [14]: parse_expr("Y + E", local_dict={'E':Symbol('E')}).free_symbols
Out[14]: {E, Y}
https://docs.sympy.org/latest/modules/parsing.html#sympy.parsing.sympy_parser.parse_expr
假设出于某种原因您需要或更喜欢将 E 或 SymPy 的任何其他保留字母作为符号。所以当你问 sympy.sympify("E") 时,你想要 <class 'sympy.core.symbol.Symbol'>
而不是 <class 'sympy.core.numbers.Exp1'>
。一个简单的小例子看下面的代码。
import sympy
symbols_list = sympy.symbols(' '.join(["A","E","Y"]))
expr = sympy.sympify("Y + 2 * E")
print(f"variables in expr are {expr.free_symbols}")
for x in symbols_list:
print(f"coefficient of {x} in expr is {expr.coeff(x)}")
那么打印出来的信息就是
variables in expr are {Y}
coefficient of A in expr is 0
coefficient of E in expr is 0
coefficient of Y in expr is 1
趁我想看的时候
variables in expr are {Y, E}
coefficient of A in expr is 0
coefficient of E in expr is 2
coefficient of Y in expr is 1
有没有办法强制 SymPy 在脚本开头声明一些东西以忘记它在这个脚本中的 E?
您应该直接使用 parse_expr
而不是 sympify
来自定义解析器的行为。使用 parse_expr
,您可以指定在执行解析代码时要使用的 local_dict
和 global_dict
。在这种情况下,它是定义 E
的 global_dict
,但您可以使用 local_dict
:
In [14]: parse_expr("Y + E", local_dict={'E':Symbol('E')}).free_symbols
Out[14]: {E, Y}
https://docs.sympy.org/latest/modules/parsing.html#sympy.parsing.sympy_parser.parse_expr