定义多项式函数



如何定义一个函数 - 比如说,def polyToString(poly) - 以标准形式返回包含多项式poly的字符串?

例如:由 [-1, 2, -3, 4, -5] 表示的多项式将返回为:

"-5x**4 + 4x**3 -3x**2 + 2x**1 - 1x**0"
def polyToString(poly):
    standard_form=''
    n=len(poly) - 1
    while n >=0:
        if poly[n]>=0:
            if n==len(poly)-1: 
                standard_form= standard_form + '   '+ str(poly[n]) + 'x**%d'%n 
            else:
                standard_form= standard_form + ' + '+str(poly[n]) + 'x**%d'%n
        else:
            standard_form= standard_form + ' - ' + str(abs(poly[n])) + 'x**' + str(n)
        n=n-1
    return standard_form

为什么这么难?

def poly_to_str(coefs):
    return ''.join(['{:+d}x**{:d}'.format(a,n) for n, a in enumerate(coefs)][::-1])

解释

  • enumerate(coefs)给了我们na ax**n性病形式成员
  • '{:+d}x**{:d}'.format(a,n)格式每个成员
  • {:+d}说打印带符号的十进制数
  • [..][::-1]反转成员数组
  • ''.join(..)将它们连接成一个字符串

print poly_to_str([-1, 2, -3, 4, -5])

输出

-5x**4+4x**3-3x**2+2x**1-1x**0

对于初学者来说可能更容易阅读的东西。

def poly2str(coefs):
    retstr=""
    for i in range(len(coefs)):
        if coefs[i] < 0:
            retstr += " -" + str(abs(coefs[i])) + "x**" + str(len(coefs) - i) + " "
        else:
            retstr += "+ " + str(abs(coefs[i])) + "x**" + str(len(coefs) - i) + " "
    return retstr

最新更新