如果方程是(-3+5(,我如何将其转换为前缀?它的运算符在方程前面。
如果使用srepr
打印未赋值表达式,它将准确显示该表达式在SymPy/Python:中的表示方式
>>> from sympy import srepr, Add
>>> srepr(Add(-3,5,evaluate=False))
'Add(Integer(-3), Integer(5))'
我猜你不想要这个。处理打印的最常见方法是创建一个自定义打印机(您必须检查相关文档(。或者,根据你想处理的案件的复杂程度,你可以处理这样一个简单的案件:
>>> from sympy import Add, Mul, S, Symbol
>>> ops = {Add: '+(%s, %s)', Mul: '*(%s, %s)'}
>>> def pr(eq):
... eq = S(eq)
... if eq.func not in ops: return str(eq)
... a, b = eq.as_two_terms()
... return ops[eq.func] % (pr(a), pr(b))
>>> pr(x + y)
'+(x, y)'
>>> pr(3*x + y - z)
'+(y, +(*(-1, z), *(3, x)))'
有一种替代方法可以处理文字数字,使其表现得像符号:创建名称为数字字符串的符号,例如
>>> a, b = (-3, 5)
>>> pr(a + b) # -3 + 5 collapses automatically to 2
'2'
>>> a, b = [Symbol(str(i)) for i in (a,b)] # create symbols from numbers
>>> pr(a + b)
'+(-3, 5)'