Non-commutative expansion of brackets (Python)

85 views Asked by At

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.

2

There are 2 answers

0
Davide_sd On BEST ANSWER

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
0
Aravind Pillai On

Try with "sympy.nc"

from sympy import symbols
from sympy.nc import NC

x, y = symbols('x y')
nc_x = NC(x)
nc_y = NC(y)

expression = nc_x * nc_y + nc_y * nc_x + nc_y ** 2 + nc_x ** 2
print(expression)