Python中多项式系数的去除与替换

2024-04-16 23:19:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我在使用python的list函数处理多项式时遇到了一些问题。在

例如,如果我写poynomial 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

Tags: 函数命令stringlistfinal术语term系数
3条回答

你也可以这样做

def unity(num):
    if num==1:return('')
    elif num=='':return('.1')
    return num

coeffs = [3,2,0,1,6] #6x^4 + 1x^3 + 0x^2 + 2x + 1
variables = ['x^4','x^3','x^2','x','']

output = ' + '.join([str(unity(i))+unity(j) for i,j in zip(coeffs[::-1],variables) if i])
print(output)
>>>'6x^4 + x^3 + 2x + 3.1'

还有一种方法可以处理这个标志:

>>> 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

这里有一个线性函数,它可以将一个列表转换成一个多项式,并具有系数的正确条件

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

^{pr2}$

按相反的顺序打印(先用高次幂):

    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)

相关问题 更多 >