I am doing this which is supposed to be an easy problem and which I think my code should be correct but for some reasons it is not working. May anyone help correcting my mistakes? How should I write the correct code?
This is the question:
Write a function that takes a polynomial in the variable x as input and computes its degree. Using a pattern test your function should print an error message when the input is not a polynomial. (It is acceptable if your function regards a string object such as "Math" as a polynomial of degree zero).
My answer:
If[Function[y, PolynomialQ[y, x]][x^2 + 3 x], Exponent[y, x], Print["error"]]
My code always returns zero and I have no idea why. Also, do we have to use Function[] to write a function?
Many thanks in advance for all the helps!
Edit:
Thanks @0x4A4D for suggestion.
Here is my edited code:
If[Function[x, PolynomialQ[x^2, x]], Exponent[y, x], Print["error"]]
which I think doesn't quite make any sense, the code does not even produce any output. I guess something is wrong with Function[], but not sure how. I would be grateful if anyone could lend some help. I have been doing this question for quite a long time. Thanks!
PolynomialQ[]
is intended to be used directly; that is,PolynomialQ[x^2 + 3 x, x]
.Exponent[y, x]
is necessarily $0$; I see nox
whatsoever in the first argument... $\endgroup$x
iny
, last I checked... if you'd assignedy
to something withx
in it, likey = x^2 + 3 x;
, then you're cooking. $\endgroup$polynomialDegree[poly_, x_] /; PolynomialQ[poly, x] := (* stuff *)
. $\endgroup$