pythonsympycommutativity

Non-commutative expansion of brackets (Python)


I wanted to ask whether there is a method to expand brackets in Python non-commutatively. For example, INPUT (x+y)**2, OUTPUT x**2 + x*y + y*x + y**2,

instead of the usual output x**2 + 2*x*y + y**2.

SymPy gives this commutative output, but I have seen that a non-commutative output is possible in Mathematica (NonCommutativeMultiply). Could anyone suggest some Python code which will expand brackets non-commutatively? It would be a big help.


Solution

  • You have to create non-commutative symbols:

    from sympy import *
    x, y = symbols("x, y", commutative=False)
    expr = (x+y)**2
    expr = expr.expand()
    print(expr)
    # out: x*y + x**2 + y*x + y**2