# Replacement rules for powers of a symbol

Suppose, I have an expression like so:

In:= expr = 2 + 5*q + q^2 + 8 q^3 + 19 q^7

Out= 2 + 5 q + q^2 + 8 q^3 + 19 q^7


Now I want to take all powers of q lying between 0 and 2 to zero i.e. my desired output is:

$8 q^3 + 19 q^7$

I tried the following without success:

In:= expr /. q^n_. /; 0 <= n <= 2 -> 0

Out= 2


What could be a neat way to do it? I know the following works:

In:= Plus @@ (If[0 <= Exponent[#, q] <= 2, 0, #] & /@ List @@ expr)

Out= 8 q^3 + 19 q^7


I just wanted to do this with simple pattern matching and replacement.

Any help will be appreciated.

There are already several good answers. Here are three other possibilities that are closer to what OP had in mind:

exp = 2 + 5 q + q^2 + 8 q^3 + 19 q^7;
exphold = HoldForm[2 q^0 + 5 q + q^2 + 8 q^3 + 19 q^7];

Replace[exp, q^n_. /; 1 <= n <= 2 -> 0, {2}] - (exp /. q -> 0)
Replace[q exp // Expand, q^n_. /; 1 <= n <= 3 -> 0, {2}]/q // Expand
Replace[exphold, q^n_. /; 0 <= n <= 2 -> 0, {3}] // ReleaseHold


all of which return 8 q^3 + 19 q^7, as expected.

For fun:

FromDigits[
Reverse[CoefficientList[exp, q] Table[Boole[Not[0 <= n <= 2]], {n, 0, Exponent[exp, q]}]]
, q]
Sum[q^n/n! (D[exp, {q, n}] /. q -> 0), {n, 3, Exponent[exp, q]}] // Expand


which also return 8 q^3 + 19 q^7.

• Nice implementations! I particularly like the second one. – Subho Apr 24 '18 at 4:13

Ignoring your requirement of using simple replacement rules, you could do:

Normal @ Series[expr, {q, Infinity, -3}]


8 q^3 + 19 q^7

expr = 2 + 5*q + q^2 + 8 q^3 + 19 q^7;
vars = Variables[expr];
FromCoefficientRules[
Select[CoefficientRules[expr, vars], First[First[##]] > 2 &], vars]


For large expressions you can convert output of CoefficientRules to Associations, and then manipulate Key/Value pairs. That would result into very fast program.

Integrate[D[expr,{q,3}],q,q,q]

• Clever piece of code! – Subho Apr 24 '18 at 14:18
• @Subho95 : Used this recently to kill off only the $0^\text{th}$ and $1^\text{st}$ powers in a Laurent polynomial. – Eric Towers Apr 24 '18 at 14:24

Another answer using pattern matching and replacement:

{expr /. {q^2 -> 0, _ q -> 0}} - Cases[expr, _?NumberQ]
Part[%,1]
8 q^3 + 19 q^7


• you can change $_^2$ by $q^2$, however not sure if powerful enough. – Gluoncito Apr 24 '18 at 3:37