You can use the common subexpression (cse) function in SymPy to perform this task.
>> from sympy import * >> from sympy.abc import * >>> k = 2*a + b*c + 4*(a + 3*d) >>> l = (b*c) + 2*(c + 3*d) >>> cse([k, l]) ([(x0, b*c + d)], [6*a + 11*d + x0, 2*c + 5*d + x0]) The result got by SymPy is not exactly the same as the one you posted but is similar in the number of multiplications and additions. On Monday, April 3, 2017 at 8:57:54 PM UTC+5:30, Pfaeff wrote: > > Hi there, > > > I just started using sympy for a small code optimization problem that I > have. > > Let's say I have a bunch of simple, linear expressions (I made these up > just as an example): > > 2 * a + (b * c) + 4 * (a + 3 * d) > > (b * c) + 2 * (c + 3 * d) > > ... > > I now want to identify common operations in this set of expressions and > combine them in order to minimize the number of arithmetic operations in my > program: > > y = b * c > z = 3 * d > > 2 * a + y + 4 * (a + z) > y + 2 * (c + z) > > > Does sympy have a built-in way to do this? If it doesn't, how would I go > about it? My idea was to traverse all expression trees and find the longest > common expressions or something. > Thanks in advance. > > > Greetings, > Pfaeff > > > > > -- You received this message because you are subscribed to the Google Groups "sympy" group. To unsubscribe from this group and stop receiving emails from it, send an email to [email protected]. To post to this group, send email to [email protected]. Visit this group at https://groups.google.com/group/sympy. To view this discussion on the web visit https://groups.google.com/d/msgid/sympy/135b7cbc-7117-42d3-8979-6b6f4da142e7%40googlegroups.com. For more options, visit https://groups.google.com/d/optout.
