我在使用 python 的多项式列表函数时遇到了一些问题。
例如,如果我写多项式 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"
。
Python 中有这方面的命令吗?
提前致谢。
/亚历克斯
//代码
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
最佳答案
这是另一种处理符号的方法:
>>> 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
关于python - 在 Python 中删除和替换多项式的系数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48485289/