# Filtering an expression: keeping only term with even power

In the expression $$x^2 y^2+x y^2+x^3y + 5 x^4 y^4$$ I would like to keep only the term where the variables have even power $$x^2y^2+5 x^4 y^4$$

Is there a way to do it?

I look into this post.
But once I get the operands, I don't see how to analyze the variable exponent.

edit retag close merge delete

Sort by » oldest newest most voted

Is that what you need?

var('x y');
p=(5*x^2*y^2+x*y^2+x^3*y+x^4*y^4).polynomial(QQ)
sum([v*v for v in p if forall(v.exponents(),lambda x:is_even(x))])
#x^4*y^4 + 5*x^2*y^2

more

@archrzesz Exactly what I want, thank you. Is there a way to keep the coefficient of each monomial? For example, return $5 x^4 y^4$.

I've edited my answer according to the Nicolas request. Notice that my answer works for many variables. Just change var and p.

The following also works, although it might not be as flexible as the answer by @achrzesz, which handles things nicely.

x, y = var('x, y')
f(x,y)=x^2*y^2-4*x^2*y+2*y^2+4*x*y^4-3*x^4*y^6
g(x,y)=(f(x,y)+f(-x,y))/2
h(x,y)=(g(x,y)+g(x,-y))/2
h

more

Here is an answer using the list command and some list comprehensions.

var('x y')
R.<x,y>=PolynomialRing(RR)
q=x^2*y^2+x+x^2*y+y^2
terms=list(q)
ans=[t*t for t in terms if (t.degree(x) % 2)==0 and (t.degree(y) % 2==0)]
sum(ans)


This will also keep the coefficients.

more