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