只用Python创建多项式类

1 投票
2 回答
7656 浏览
提问于 2025-04-29 20:34

我一直在做一个多项式的类,这个类里有 def __mul__(self, other)def __rmul__(self, other)def derivative(self) 这些方法,但一直没能搞定。有人能教我怎么做吗?需要注意的是,self 和 other 的系数长度可能不一样。目前我有这个:

class Polynomial(object):
    def __init__(self, coeffs):
        # if coeffs == [2,-3,5]:  2x**2-3*x+5
        self.coeffs = coeffs

    def almostEqual(d1, d2):
        epsilon = 0.000001
        return abs(d1 - d2) < epsilon

    def firstNonZeroCoeff(self, coeffs): 
        coeffs = self.coeffs
        for num in xrange(len(coeffs)): #loop through all coeffs
            if coeffs[num]!=0: #check if is 0
                return coeffs[num]

    def degree(self):
        return len(self.coeffs)-1

    def coeff(self, power):
        return self.coeffs[self.degree()-power]

    def evalAt(self, x):
        return sum([self.coeff(power)*x**power
                    for power in xrange(self.degree()+1)])

    def __add__(self, other):
        # First, made both coefficent lists the same length by nondestructively
        # adding 0's to the front of the shorter one
        (coeffs1, coeffs2) = (self.coeffs, other.coeffs)
        if (len(coeffs1) > len(coeffs2)):
            (coeffs1, coeffs2) = (coeffs2, coeffs1)
        # Now, coeffs1 is shorter, so add 0's to its front
        coeffs1 = [0]*(len(coeffs2)-len(coeffs1)) + coeffs1
        # Now they are the same length, so add them to get the new coefficients
        coeffs = [coeffs1[i] + coeffs2[i] for i in xrange(len(coeffs1))]
        # And create the new Polynomial instance with these new coefficients
        return Polynomial(coeffs)

非常感谢!

暂无标签

2 个回答

0

这可能不是最漂亮的实现方式,但看起来是有效的。

def derivative(self):
    # Copy coefficeints to a new array
    der = list(self.coeffs)
    # (ax^n)' = (n)ax^(n-1)
    # 1. ax^n -> ax^(n-1)
    print der
    der.pop(0)
    print der
    # 2. ax^(n-1) -> (n)ax^(n-1)
    for n in range(1,self.degree()+1):
        der[n-1] *= n
    return Polynomial(der)
1

两个多项式相乘的时候,需要用到嵌套循环。也就是说,对于第一个多项式P1中的每一个项,你都要把它的系数和第二个多项式P2中的所有项的系数相乘。然后把所有的中间结果加起来。你可以为了乘法的需要,创建一些中间的多项式。最后,把这些结果全部加在一起。

这里有一个很好的示例,可以参考一下:点击这里

先确保你的代码能正确运行,然后再进行优化。祝你好运!

撰写回答