10

I have a set of sympy expressions like this (a few hundred of them):

>>> foo = parse_expr('X | Y')
>>> bar = parse_expr('(Z & X) | (Z & Y)')
>>> baz = parse_expt('AAA & BBB') # not needed for this example; just filler

I can simplify one in isolation:

>>> simplify(bar)
Z & (X | Y)

Is there a way to simplify, including the whole set of variables available?

>>> mysimplify(bar, include=(foo,bar,baz))
Z & foo
ajwood
  • 18,227
  • 15
  • 61
  • 104

1 Answers1

4

You can take advantage of Common Subexpresion Elimination. You must use it in combination with simplify by combining all your expressions into a single artificial expression (for example, by passing them as arguments to a fictitious function). I don't think that it will always work as desired, however on a loose analogue of your example it produces the expected result:

In [1]: from sympy import *

In [2]: myexprlist = sympify('listofexpr(x|y, (z&x)|(z&y))')

In [3]: cse(simplify(myexprlist))
Out[3]: ([(x0, Or(x, y))], [listofexpr(x0, And(x0, z))])

The first entry in the result is a list of introduced subexpressions. In this case the subexpression x|y has been denoted with x0. The second part of the result is the simplified expression (packaged into a list, since the input can be a list of expressions).

Leon
  • 31,443
  • 4
  • 72
  • 97