glS
glS

Reputation: 1299

Make all symbols commutative in a sympy expression

Say you have a number of non commutative symbols within a sympy expression, something like

a, c = sympy.symbols('a c', commutative=False)
b = sympy.Symbol('b')
expr = a * c + b * c

What is the preferred way to make all symbols in the expression commutative, so that, for example, sympy.simplify(allcommutative(expr)) = c * (a + b)?

In this answer it is stated that there is no way to change the commutativity of a symbol after creation without replacing a symbol, but maybe there is an easy way to change in blocks all symbols of an expression like this?

Upvotes: 2

Views: 955

Answers (2)

smichr
smichr

Reputation: 19135

Two comments:

  1. noncommutatives will factor (though they respect the side that the nc expr appears on)
  2. although you have a robust answer, a simple answer that will often be good enough is to just sympify the string version of the expression

Both are shown below:

>>> import sympy
>>> a, c = sympy.symbols('a c', commutative=False)
>>> b = sympy.Symbol('b')
>>> expr = a * c + b * c
>>> factor(expr)
(b + a)*c
>>> S(str(_))
c*(a + b)

Upvotes: 3

user6655984
user6655984

Reputation:

If you want Eq(expr, c * (a + b)) to evaluate to True, you'll need to replace symbols by other symbols that commute. For example:

replacements = {s: sympy.Dummy(s.name) for s in expr.free_symbols}
sympy.Eq(expr, c * (a + b)).xreplace(replacements).simplify()

This returns True.

Upvotes: 5

Related Questions