pythonsympycommutativity

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?


Solution

  • 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.