仅创建多项式类Python

时间:2014-10-27 05:35:50

标签: python class python-2.7 methods static-methods

我一直在研究包含def __mul__(self, other)def __rmul__(self, other)def derivative(self)的多项式类很长一段时间但无济于事。有人可以告诉我它是如何完成的吗?注意,自身和其他系数的长度可以不同。到目前为止,我有这个:

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 :(得分:1)

两个多项式的乘法将是嵌套循环。对于P1中的每个项,您需要将其系数乘以所有P2的系数。然后添加所有中间结果。您可以为乘法创建中间多项式。然后将它们全部加在一起。

有一个很好的例子here

首先使其正常工作,然后进行任何优化。祝你好运

答案 1 :(得分: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)