# Function to return powers of polynomial

I wish to write a function which inputs a polynomial f[x] and outputs the powers of x which appear. (There might be a build in function for this but I want to learn to do this myself).

Initially I have

ClearAll[powers];
powers[m_] := m /. Plus -> List


Now I am faced with a problem I come against regularly. The naive next step is to define a rule

rule1={coeff_ x^pwr -> pwr}


but this wont work on some terms. If my polynomial is

a0 x^2 + a_1 x +a_2


Then my rule will only affect the first term because for example the second term is understood by mathematica as

Times[a1,x]


and not

Times[a1,Power[x,0]]


which my rule acts on. I can get around this by extending my rule to

rule1={coeff_ x^pwr -> pwr,coeff_ x -> 1}


but if a1=1 then this is still not enough and would need to use

rule1={coeff_ x^pwr -> pwr,coeff_ x -> 1,x -> 1}


Finally, none of my rules apply to the constant term and the only way I can see around this is to again extend my rule again, and I haven't even figured out what the correct rule is yet.

So my question is: is there a more straightforward way to define a rule which does what I want?

EDIT: I see that I can get around this issue by simply removing any problems which could arise, i.e. making sure everything has a coefficient not equal to 1 and a power greater than 1. So I could use

ClearAll[powers];
powers[m_] := a x^2 m //. Plus -> List /. {coeff_ x^pwr_ -> pwr - 2}


which works exactly as I require. But I still have my original issue in general.

• You can get the constant term by the replacement x -> 0... – Henrik Schumacher Jun 20 '18 at 12:11

With pattern matching, this is pretty complicated. You may look at default values.

A simpler solution is:

pol= 2+x + 4 x^2 + 5 x^3 - x^4;
Exponent[#, x]& /@ List @@ pol

(*{0,1,2,3,4}*)


And another solution:

Cases[Expand[x^2 pol], x^n_:>n, Infinity]-2
(* {0,1,2,3,4} *)