I am not good in patterns in Mathematica, and so can't figure what I am doing wrong.
This example works, when the exponent is 1
ClearAll[y,x,n]
Cases[{( y[x]/x)^1}, (y[x]/x )^(n_.) :> n]
But when exponent is 2
it does not find it
Cases[{( y[x]/x)^2}, (y[x]/x )^(n_.) :> n]
Help says
I think this happens, because the font end changes (y[x]/x)^2
to y[x]^2/x^2
before Cases
gets hold of it? So the pattern is lost. But when I tried
Cases[{( y[x]/x)^2}, (y[x]^n_.)/(x^n_.):>n]
It still returned {}
What is the correct way to handle this? I need to find all powers of expressions of form y[x]/x
Tried HoldForm
and Verbatim
and Inactive
but can't get it to work.
Addition This is really an observation and some rambling on my part about this issue. Did not want to put it as comment.
Answer by m_goldberg explains the problem (which comes down to knowing how Mathematica internally layout this expression, i.e. FullForm basically).
But When the exponent is a symbol, then it behaves differently
Cases[{(y[x]/x)^a},(y[x]/x)^(n_):>n]
This is because of the difference in FullForm between
FullForm[(y[x]/x)^a]
FullForm[(y[x]/x)^2]
I would have expected then when the exponent is a
, the FullForm should similar to when the exponent is a number, i.e. as follows
Times[Power[x,-a],Power[y[x],a]]
Or
So my lesson for the day, when using pattern in Mathematica, I need to look at FullForm to get the pattern right because what I see might not be what I think it is.
Cases[{(y[x]/x)^3}, Times[Power[x_, b_], Power[y_, c_]] :> Abs[b]]
$\endgroup$Cases[{( y[x]/x)^2}, (y[x]/x )^(n_.) :> n]
does not? I am writing the pattern as the expression appears. Also help saysx^n_.
should match. I guess the question becomes, when should one use theFullForm
for the pattern, vs. the "form" that appears on the screen that one is looking at. This is the confusing part about patterns in Mathematica. $\endgroup$