Ask Your Question

Filtering an expression: keeping only term with even power

asked 2012-10-22 12:26:25 -0500

Nicolas Essis-Breton gravatar image

updated 2012-10-22 13:27:36 -0500

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 flag offensive close merge delete

3 answers

Sort by » oldest newest most voted

answered 2012-10-22 13:30:05 -0500

achrzesz gravatar image

updated 2012-10-22 20:12:59 -0500

Is that what you need?

var('x y');
sum([v[0]*v[1] for v in p if forall(v[1].exponents()[0],lambda x:is_even(x))[0]])
#x^4*y^4 + 5*x^2*y^2
edit flag offensive delete link 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$.

Nicolas Essis-Breton gravatar imageNicolas Essis-Breton ( 2012-10-22 13:42:54 -0500 )edit

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

achrzesz gravatar imageachrzesz ( 2012-10-22 20:14:50 -0500 )edit

@achrzesz Very flexible approach. Thank you.

Nicolas Essis-Breton gravatar imageNicolas Essis-Breton ( 2012-10-23 00:35:57 -0500 )edit

answered 2012-10-22 21:27:21 -0500

calc314 gravatar image

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')
edit flag offensive delete link more

answered 2012-10-22 13:46:14 -0500

calc314 gravatar image

updated 2012-10-22 13:47:32 -0500

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

var('x y')
ans=[t[0]*t[1] for t in terms if (t[1].degree(x) % 2)==0 and (t[1].degree(y) % 2==0)]

This will also keep the coefficients.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools


Asked: 2012-10-22 12:26:25 -0500

Seen: 172 times

Last updated: Oct 22 '12