Ask Your Question

leading coefficient polynomial

asked 2016-10-02 11:27:48 -0600

this post is marked as community wiki

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 flag offensive close merge delete

4 answers

Sort by ยป oldest newest most voted

answered 2016-10-03 12:03:41 -0600

If you have


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


to find out how to use it.

edit flag offensive delete link more

answered 2016-12-11 03:47:00 -0600

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

edit flag offensive delete link more

answered 2016-10-03 09:17:11 -0600

Mafra gravatar image

For example,


you can extract its coefficients as follows:


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:


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

edit flag offensive delete link more

answered 2016-10-02 13:13:08 -0600

tmonteil gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools


Asked: 2016-10-02 11:27:48 -0600

Seen: 506 times

Last updated: Dec 11 '16