python - 在 Python 中删除和替换多项式的系数

标签 python list math coefficients

我在使用 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/

相关文章:

javascript - 如何使用 jquery 按字母顺序对多层列表进行排序

vb.net - 优化除法/指数计算

algorithm - 一场有100个对手的比赛,赢尽可能多的钱

python - Python中分组数据的累积自定义函数

python - 贪婪的正则表达式每第 n 行拆分 python

python - 在python中,什么更有效率?修改列表或字符串?

使用 numpy 的 Python 微分不产生预期的输出

python - 复杂转换为 Python Complex

Python:匹配字符串并就地替换

java - 使用JAVA形成测试数据列表进行selenium功能测试