[英]Print the entire expression object of sympy when changes in internal structure occur
So as the question says i want to print an entire expression object when internal structure of its tree changes, but as the sympy objects are immutable i cannot to do this with the name the object is bound to 因此,正如问题所述,我想在树的内部结构发生变化时打印整个表达式对象,但是由于sympy对象是不可变的,因此我无法使用对象绑定到的名称来执行此操作
Here is an example of Code on how i am changing the Internal Structure 这是关于我如何更改内部结构的代码示例
from sympy import *
from sympy.abc import x,y
input = 'x*(x+4)+3*x'
expr = sympify(input,evaluate=False)
def traverse(expr):
if(expr.is_Number):
return 1,True
oldexpr = expr
args = expr.args
sargs = []
hit = False
for arg in args:
arg,arghit = traverse(arg)
hit |= arghit
sargs.append(arg)
if(hit):
expr = expr.func(*sargs)
return expr,True
else:
return oldexpr,False
print(srepr(expr))
expr,hit = traverse(expr)
print(expr)
here i am changing the number to 1 whenever i encounter a number in the expression tree. 在这里,只要我在表达式树中遇到一个数字,就将数字更改为1。 And i want to print the complete expression when i made the change like this: x*(x+1)+3*x
and then x*(x+1)+x
Can anyone suggest me on how to achieve this. 我想在进行如下更改时打印出完整的表达式: x*(x+1)+3*x
,然后x*(x+1)+x
有人可以建议我如何实现这一点。
Just a slight mod to what you have might be what you are looking for: 只是稍微修改一下您所拥有的,可能就是您想要的:
def traverse(expr):
if any(a.is_Number and abs(a) != 1 for a in expr.args):
print(expr,'->',expr.func(*[(a if not a.is_Number else 1) for a in expr.args]))
if expr.is_Number and abs(expr) != 1:
return 1, True
oldexpr = expr
args = expr.args
sargs = []
hit = False
for arg in args:
arg,arghit = traverse(arg)
hit |= arghit
sargs.append(arg)
if(hit):
expr = expr.func(*sargs)
return expr, True
else:
return oldexpr, False
This produces 这产生
>>> traverse(2*x+3)
(2*x + 3, '->', 2*x + 1)
(2*x, '->', x)
(x + 1, True)
/c /C
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.