Python-当评估=假时表达式相等性检查的Sympy问题 [英] Python- Sympy Issue with expression equality check when evaluate=False
问题描述
在我的项目中,当我创建任何 Add
或 Mul
对象时,我必须使用 evaluate=false
.在这种情况下,当我对这些对象应用相等性检查时,我遇到了问题.问题在于参数的顺序.
In my project I have to use evaluate=false
at the time when i am creating any Add
or Mul
objects. In this case I am facing a problem when I apply equality checks on these objects. The issue is because of the ordering of the arguments.
请考虑以下示例:
k2=Mul(*[x,y,2],evaluate=False)
k1=Mul(*[x,2,y],evaluate=False)
print k1==k2
结果是 false
因为 k2.args
是 (x,y,2)
和 k1.args
> 是 (x,2,y)
.因此,当比较检查元组相等性时,它返回 false
.有什么办法可以得到想要的结果吗?
The result is false
as k2.args
are (x,y,2)
and k1.args
are (x,2,y)
.
So, while the comparison checks for tuple equality it returns false
.
Is there any way I can get the wanted result?
另外,如果我对元组进行一些操作(比如颠倒顺序然后检查),它会在 k1
和 k2
由不同的Mul
对象(例如 k1.args
= 2*x,y
和 k2.args
= 2*y,x
)
Also, if I put some operation on tuples (like reversing the order and then checking), it fails in the cases when k1
and k2
are formed from different Mul
objects (like when k1.args
= 2*x,y
and k2.args
= 2*y,x
)
我不能在这里使用排序,在这种情况下 Add([x+y,z],evaluate=False)
和 Add([x+z,y],evaluate=False)
将是两个不同的表达式.另外,如果我使用 evalaute=True
,在这种情况下 Add([x+y],x])
和 Add([2*x+y])
将是相同的,这是我不想要的.
I can't use sorting here , as in this case Add([x+y,z],evaluate=False)
and Add([x+z,y],evaluate=False)
will be two different expressions. Also if i use evalaute=True
, in this case Add([x+y],x])
and Add([2*x+y])
will be the same, which i don't want.
推荐答案
找到了一个解决方法.
在表达式形成的 Add/Mul 类中使用以下代码展平所有参数
in Add/Mul classes at the expression formation flatten all arguments using below code
flatten_args = []
for arg in args:
if (arg.__class__==cls):
flatten_args.extend(arg.args)
else:
flatten_args.append(arg)
obj = Expr.__new__(cls, *flatten_args)
并且在进行相等性检查时,我将进行额外检查首先对 args 列表进行排序 arg_list.sort()
然后比较两个列表
and at the time of equality check ,i am putting one extra check
sort the args list first arg_list.sort()
and than compare two lists
这篇关于Python-当评估=假时表达式相等性检查的Sympy问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!