这次将一些方法放在一起会给出一个很好的答案。有趣的是,看看这种策略是否比您生成的方程式更有效,或者顾名思义,这次只是幸运的结果。
def iflfactor(eq):
"""Return the "I'm feeling lucky" factored form of eq."""
e = Mul(*[horner(e) if e.is_Add else e for e in
Mul.make_args(factor_terms(expand(eq)))])
r, e = cse(e)
s = [ri[0] for ri in r]
e = Mul(*[collect(ei.expand(), s) if ei.is_Add else ei for ei in
Mul.make_args(e[0])]).subs(r)
return e
>>> iflfactor(eq) # using your equation as eq
2*x*y*z*(x**2 + x*y + y**2 + (z - 3)*(x + y + z) + 3)
>>> _.count_ops()
15
顺便说一句,factor_terms和gcd_terms之间的区别在于,factor_terms在保留表达式的原始结构的同时,将更努力地提取通用术语,就像您手动操作一样(即在可以拉出的Adds中查找通用术语) 。
>>> factor_terms(x/(z+z*y)+x/z)
x*(1 + 1/(y + 1))/z
>>> gcd_terms(x/(z+z*y)+x/z)
x*(y*z + 2*z)/(z*(y*z + z))
物有所值,
克里斯