2014-10-27 98 views
1

我一直在研究包含def __mul__(self, other)def __rmul__(self, other)def derivative(self)多項式的多項式類,但都無濟於事。有人能告訴我它是如何完成的嗎?請注意,自身和其他係數的長度可能不同。到目前爲止,我有這個:創建多項式Python僅

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) 

非常感謝!

回答

1

兩個多項式的乘法將是一個嵌套循環。對於P1中的每一項,都需要將其係數乘以所有P2的係數。然後添加所有的中間結果。你可以爲了乘法而創建中間多項式。然後將它們加在一起。

有一個很好的工作實例here

使其工作權,然後再做任何優化。祝你好運

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)