2014-12-05 116 views
0

我已经写了一个小类,其初始化程序需要作为参数的字典。以下字典{2:3, 4:5, 6:7}转换为多项式3x^2 + 5x^4 + 7x^6,因此我的字典的键是指数,它的值是系数。在Python中使用多项式乘以字典

我已经成功设法使用eq方法在我的类中实现了两个多项式的比较,并且我可以添加它们。这里是我的代码:

class Polynomial(object): 
def __init__(self, polynom = {}): 
    self.polynom = polynom 
    self.poly_string = self.nicePolynom(polynom) #just a method that will make my output look nice 

def __str__(self): 
    return self.poly_string # for debugging purposes 

def coefficient(self, exponent): 
    """ 
    A small function that returns the coefficient of the corresponding exponent 

    i.e. if our Polynomial is P = 3x^9 then p.coefficient(9) return 3 
    """ 
    try: 
     return self.polynom[exponent] 
    except KeyError: 
     pass 

def __add__(self,other): 
    """ 
    Overloading the + operator 

    Not the most elegant solution but easily understandable. 
    We check first if our exponent is present in both polynomials 
    then if its only present in one and the symmetric case, adding the result 
    to the dictionary add 
    """ 
    add = {} 

    for exponent in self.polynom: 
     if exponent in other.polynom: 
      add[exponent] = self.polynom[exponent] + other.polynom[exponent] 

    for exponent in self.polynom: 
     if exponent not in other.polynom: 
      add[exponent] = self.polynom[exponent] 

    for exponent in other.polynom: 
     if exponent not in self.polynom: 
      add[exponent] = other.polynom[exponent] 
    return add 

def __mul__(self, other): 

    mult = {} 

    for exponent1 in self.polynom: 
     for exponent2 in other.polynom: 
      mult[exponent1 + exponent2] = self.coefficient(exponent1) * other.coefficient(exponent2) 

    return mult 

的关键一步,我的主要问题是乘法期间我想利用加。但是我对OOP完全陌生,而且我也没有看到我现在可以如何初始化一个Polynom对象,以便我可以执行加法运算。

如果我在获得正确指数的那一刻乘上一个多项式本身,但除了初始项和结束项之外,所有的系数都是关闭的。

+0

系数已关闭,因为扩展中的多个术语对答案中的相同功能作出了贡献,并且在此情况下您将在同一个指数键上重写'mult'条目。 'exponent1,exponent2 = 1,3',然后是'exponent1,exponent2 = 2,2'时会发生什么? – xnx 2014-12-05 21:30:34

+0

我同意@xnx,但我不明白如何解决它,有没有简单的方法来防止这与if/else参数? – Spaced 2014-12-05 21:32:23

+0

如果这是一个学习练习,那么尽一切办法去做。但是如果你想用这个来认真对待任何事情,我的建议不是重新发明轮子,而只是看看[sympy](http://docs.sympy.org/latest/tutorial/intro.html ),它处理多项式(除其他外)非常好。 – 2014-12-06 01:13:23

回答

2

这里有一个方法可能工作:

for exponent1 in self.polynom: 
    for exponent2 in other.polynom: 
     this_exponent = exponent1 + exponent2 
     this_coeff = self.coefficient(exponent1) * other.coefficient(exponent2) 
     try: 
      mult[this_exponent] += this_coeff 
     except KeyError: 
      mult[this_exponent] = this_coeff 

也就是说,更新新的动力系数,并赶上时引发第一次遇到一个电源来初始化字典,相应的异常指数密钥。 (这是更多的“Pythonic”,如果你关心这样的事情,if..else条款)。