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
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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With