Collect as an expression expression in Sympy

I am currently dealing with the functions of more than one variable and you need to collect similar terms in an attempt to simplify the expression.

Say the expression is expressed as follows:

x = sympy.Symbol('x')
y = sympy.Symbol('y')
k = sympy.Symbol('k')
a = sympy.Symbol('a')

z = k*(y**2*(a + x) + (a + x)**3/3) - k((2*k*y*(a + x)*(n - 1)*(-k*(y**2*(-a + x) + (-a + x)**3/3) + k*(y**2*(a + x) + (a + x)**3/3)) + y)**2*(-a + k*(n - 1)*(y**2 + (a + x)**2)*(-k*(y**2*(-a + x)))))
zEx = z.expand()
print type(z)
print type(zEx)

EDIT: formatting to add clarity and modified the expression z to facilitate understanding of the problem.

Say it zcontains so many terms that sift them through the eye. and choosing the appropriate terms will take an unsatisfactory amount of time.

I want to collect all terms that are ONLY multiples of ** **. I do not need quadratic or higher powers of a, and I do not need terms that do not contain a.

Type zand zExreturns the following:

print type(z)
print type(zEx)
>>>
<class 'sympy.core.add.Add'>
<class 'sympy.core.mul.Mul'>

- , , a, a ^ 0 ^ 2?

tl'dr

z (x, y) a k, z zEx, (): a z a ? , , a.

+4
3

, . @asmeurer ( ). ; :

from sympy import *
from sympy.parsing.sympy_parser import parse_expr
import sys

x, y, k, a = symbols('x y k a')

# modified string: I added a few terms
z = x*(k*a**9) + (k**1)*x**2 - k*a**8 + y*x*(k**2) + y*(x**2)*k**3 + x*(k*a**1) - k*a**3 + y*a**5

zmod = Add(*[argi for argi in z.args if argi.has(a)])

zmod

a**9*k*x - a**8*k + a**5*y - a**3*k + a*k*x

, :

z.args

- ( , ):

(k*x**2, a**5*y, -a**3*k, -a**8*k, a*k*x, a**9*k*x, k**2*x*y, k**3*x**2*y)

, a, has. , Add, .

, a. , a , collect Mul:

from sympy import *
from sympy.parsing.sympy_parser import parse_expr
import sys

x, y, k, a = symbols('x y k a')

z2 = x**2*(k*a**1) + (k**1)*x**2 - k*a**8 + y*x*(k**2) + y*(x**2)*k**3 + x*k*a - k*a**3 + y*a**1

zc = collect(z2, a, evaluate=False)
zmod2 = Mul(zc[a], a)

zmod2

a*(k*x**2 + k*x + y)

zmod2.expand()

a*k*x**2 + a*k*x + a*y

.

z, , :

z3 =  k*(y**2*(a + x) + (a + x)**3/3) - k((2*k*y*(a + x)*(n - 1)*(-k*(y**2*(-a + x) + (-a + x)**3/3) + k*(y**2*(a + x) + (a + x)**3/3)) + y)**2*(-a + k*(n - 1)*(y**2 + (a + x)**2)*(-k*(y**2*(-a + x)))))
zc3 = collect(z3.expand(), a, evaluate=False)
zmod3 = Mul(zc3[a], a)

zmod3.expand():

a*k*x**2 + a*k*y**2

, ?

PS: @asmeurer !

+2

expr.args.

, a, collect , .

+1

In addition to the other answers provided, you can also use collectas a dictionary.

print(collect(zEx,a,evaluate=False)[a])

gives expression

k*x**2 + k*y**2
+1
source

All Articles