Define polynomial function

Posted by user1822707 on Stack Overflow See other posts from Stack Overflow or by user1822707
Published on 2012-11-14T04:32:46Z Indexed on 2012/11/14 5:00 UTC
Read the original article Hit count: 345

Filed under:
|

How can I define a function - say, def polyToString(poly) - to return a string containing the polynomial poly in standard form?

For example: the polynomial represented by [-1, 2, -3, 4, -5] would be returned as:

"-5x**4 + 4x**3 -3x**2 + 2x**1 - 1x**0"
def polyToString(poly):
    standard_form=''
    n=len(poly) - 1
    while n >=0:
        if poly[n]>=0:
            if n==len(poly)-1: 
                standard_form= standard_form + '   '+ str(poly[n]) + 'x**%d'%n 
            else:
                standard_form= standard_form + ' + '+str(poly[n]) + 'x**%d'%n
        else:
            standard_form= standard_form + ' - ' + str(abs(poly[n])) + 'x**' + str(n)
        n=n-1
    return standard_form

© Stack Overflow or respective owner

Related posts about python

Related posts about python-2.7