This post is a wiki. Anyone with karma >750 is welcome to improve it.

Hello everybody,

I'm new to sagemath and python in general, and one of my course in Uni uses it... I have a vague and unclear tutorial the prof gave us and for now I know only the most basic commands.

I have to write a function that takes a polynomial of any degree and tells me the coefficient of the highest degree member (for example , 2x^4+3x^3 would be 2, 7x^3+2x^4+2 would be 7...).

I think the function would have to use "expand", "degree", and of course "coefficient". But i barely have any idea as how to write it.

If anyone could help me it would be great, I am kinda lost here...

Sorry for sloppy english and thanks in advance.

edit retag close merge delete

Sort by ยป oldest newest most voted

Hint: if P is your polynomial, you should ask for its coefficients, you will get a list, the last element of that list is the leading coefficient.

more

For example,

P=7*x^3+2*x^4+2


you can extract its coefficients as follows:

P.coefficients()


to get

[[2, 0], [7, 3], [2, 4]]


So the last sublist contains the answer, in this case 2 is the coefficient of x^4.

To extract this automatically you can define a function that takes a polynomial as argument:

def get_highest_coeff(P):
m = P.coefficients()
ncoeffs = len(m)
return m[ncoeffs - 1][0]


And use it like this:

get_highest_coeff(P)


to get 2 as the answer. Hope this helps you get going!

more

If you have

P=7*x^3+2*x^4+2


then type P.[TAB] to see a list of possible "attributes" or "methods" attached to P. Other people have mentioned P.coefficients(). You might also hope that there is something like a leading_coefficient method, so try P.l[TAB] to find everything starting with the letter l. Then you should see P.leading_coefficient, so type

P.leading_coefficient?


to find out how to use it.

more

Sage trac ticket 21608 provides methods for "leading term", "leading coefficient", "leading monomial", and is available in Sage 7.5.beta6.

more