Sympy: How to minimize the number of multiplications in multivariate expressions?

浪尽此生 提交于 2021-02-19 07:43:11

问题


I have a lot of expressions which sympy default writes as sums of products of variables. These expressions can get quite long. I would like to simplify these expressions to have as few as possible multiplications. A reduced example:

from sympy import symbols, cse, factor, simplify, count_ops, collect
a,b,c=symbols("a b c", integer=True, positive=True)
e = a*a*b + a*a + a*b*b + a*b*c + 4*a*b + a*c + 3*a + b*b*c + 4*b*c + 3*c + 1

What I would like to get is something like:

(a + b + 3) * (a + c) * (b + 1) + 1

which in this case has only 3 multiplications and 5 additions.

Sympy functions such as factor don't work, because of the extra terms.

simplify keeps insisting on creating sums of simple factors, even when I experiment with the measure argument to penalize powers and multiplications.

cse only separates products of simple terms.

Is there a way to generate these kind of simplifications with sympy?

来源:https://stackoverflow.com/questions/58458832/sympy-how-to-minimize-the-number-of-multiplications-in-multivariate-expressions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!