Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing and replacing coefficients of polynomials in Python

I´m having some trouble using python´s list function for polynomials.

For example, if I write the poynomial p1 = [0, 0, 0, 1, 1], I get the output 1*x^4 + 1*x^3 + 0*x^2 + 0*x + 0

I want to adjust this so that:

  • Terms with coefficient 1 are written without the coefficients, e.g. "1x^3" should be written as "x^3".

  • Terms with coefficient 0 should not be written at all, e.g. "x^4 + x^3 + 0*x^2 + 0*x + 0" should be simplified as "x^4 + x^3".

Is there a command for this in python?

Thanks in advance.

/Alex

//the code

def polynomial_to_string(p_list):
    terms = []
    degree = 0

    for coeff in p_list:
        if degree == 0:
            terms.append(str(coeff))
        elif degree == 1:
            terms.append(str(coeff) + 'x')
        else:
            term = str(coeff) + 'x^' + str(degree)
            terms.append(term)
        degree += 1

    terms.reverse()
    final_string = ' + '.join(terms)

    return final_string
like image 478
Alexander West Avatar asked Dec 23 '22 10:12

Alexander West


2 Answers

Here's an alternative way that also deals with the sign:

>>> def getsign(n):
...     return '-' if n<0 else '+'
...
>>>
>>> def polynom(l):
...     pl = ['' if j==0 else '{}x^{}'.format(getsign(j),i) if j==1 or j==-1 else '{}{}x^{}'.format(getsign(j),abs(j),i) for i,j in enumerate(l)]
...     return ''.join([str(l[0])]+pl) if l[0]!=0  else ''.join(pl)
...
>>> print polynom([0, 0, 0, -1, -2, 1, 7])
-x^3-2x^4+x^5+7x^6
like image 168
coder Avatar answered Dec 25 '22 23:12

coder


Here is a one liner to convert a list to a polynomial with the correct conditions for coefficients

p = [0, 0, 0, 1, 1]

s = ' + '.join('%d*x^%d' % (pi, i) if pi != 1 else 'x^%d' % i for i, pi in enumerate(p) if pi != 0)

s

'x^3 + x^4'

To print in opposite order (high powers first):

    s = ' + '.join('%d*x^%d' % (pi, i) if pi != 1 else 'x^%d' % i for i, pi in reversed(list(enumerate(p))) if pi != 0)
like image 29
Gerges Avatar answered Dec 26 '22 00:12

Gerges