我在使用Python的多项式列表函数时遇到了一些问题。
例如,如果我写多项式
我想进行以下调整:
提前感谢。
/Alex
//代码
例如,如果我写多项式
p1 = [0, 0, 0, 1, 1]
,输出结果为1*x^4 + 1*x^3 + 0*x^2 + 0*x + 0
。我想进行以下调整:
系数为1的项应该省略系数,例如
"1x^3"
应该写成"x^3"
。系数为0的项不应该被写出来,例如
"x^4 + x^3 + 0*x^2 + 0*x + 0"
应该简化为"x^4 + x^3"
。
提前感谢。
/Alex
//代码
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
x^2 + -3x
,还是只需要一个减号,如x^2 - 3x
? - Rory Daulton