使用字典将Python中的多项式相乘

时间:2014-12-05 21:27:06

标签: python dictionary polynomials

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

我已经成功地使用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对象,我可以在其上执行加法运算。

如果我在得到正确的指数时我自己乘以多项式,但除了初始和结束项之外,所有系数都是偏离的。

1 个答案:

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

即,更新新功率的系数,并捕获在第一次遇到功率时引发的异常,以在相应的指数键处初始化字典。 (如果你关心这些事情,这更像是一个if..else条款的“Pythonic”。