繁体   English   中英

在 Python 中创建多项式类

[英]Creating Polynomial Class in Python

我目前正在创建一个 Polynomial 类,其中包括addmuleval方法。 我目前被困在加法部分,如果有人能给我一些关于如何解决这个问题的帮助,我将不胜感激。 目前一切正常,没有错误,但是当我执行 p3 = p1 + p2 并打印 p3 时,我将两个列表一起返回。 任何反馈将不胜感激。

class Polynomial(object):

    def __init__(self, *coeffs, num = 0):

        self.coeffs = list(coeffs) # turned into a list

        assert (type(num) is type(1)) 
        self.num = num

    # Needs to be operator overload
    '''
    def __mul__(self, other):
    '''

    def __eval__(self, other, coeff, x):
        result = coeff[-1]
        for i in range(-2, -len(coeff)-1, -1):
            result = result * x + coeff[i]
        return result


    def __add__(self, other):

        assert type(other) is Polynomial

        num = self.coeffs + other.coeffs

        return Polynomial(num)


    def __sub__(self, other):

        assert type(other) is Polynomial
        num = self.coeffs - other.coeffs

        return Polynomial(num)




    def __represntation__(self):
        return "Polynomial" + str(self.coeffs)   

    def __str__(self):
        rep = ""    
        degree = len(self.coeffs) - 1
        rep += str(self.coeffs[0]) + "x^" + str(degree)       
        for i in range(1, len(self.coeffs)-1):
            coeff = self.coeffs[i]
            if coeff < 0:
                rep += " - " +  str(-coeff) + "x^" + str(degree - i)
            else:
                rep += " + " +  str(coeff) + "x^" + str(degree - i)

            if self.coeffs[-1] < 0:
                rep += " - " + str(-self.coeffs[-1])
        else:
            rep += " + " + str(self.coeffs[-1])  
        return rep

问题在这里:

num = self.coeffs + other.coeffs

将一个列表添加到另一个列表它们连接起来。 简单地相互添加相应的元素,你想要做

from itertools import zip_longest

...

num = [a + b for (a, b) in zip_longest(self.coeffs, other.coeffs, fillvalue=0)]

我们使用zip_longest()而不是更通用的zip()因为一个多项式可能比另一个长,我们不想破坏它。 它们中的任何一个都会将相应的元素组合在一起,以便我们可以轻松地添加它们并列出这些元素。

你会为减法做类似的事情。

您不能直接添加两个列表。

def __add__(self, other):

    assert type(other) is Polynomial
    assert len(self.coeffs) != len(other.coeffs)

    new_ceffs = [item1 + item2 for (item1, item2) in zip(self.coeffs, other.coeffs)]

    return Polynomial(new_ceffs)

您应该颠倒传递给构造函数的系数的顺序,以便self.coeffs列表中的索引对应于指数。 这将简化您的其余代码,并允许您使用 zip_longest 进行加法和减法。

但是,当您进行其他操作时,我想您会意识到如果它是一本字典,您的内部结构会更容易管理。 字典对丢失条目的容忍度更高,从而避免了为新索引分配空间的担忧。

class Polynomial(object):

    def __init__(self, *coeffs):
        self.coeffs = {exp:c for exp,c in enumerate(coeffs[::-1])}
    
    def __add__(self, other):
        assert type(other) is Polynomial
        result = Polynomial(0)
        result.coeffs = {**self.coeffs}
        for exp,c in other.coeffs.items():
            result.coeffs[exp] = result.coeffs.get(exp,0) + c
        return result

    def __sub__(self, other):
        assert type(other) is Polynomial
        result = Polynomial(0)
        result.coeffs = {**self.coeffs}
        for exp,c in other.coeffs.items():
            result.coeffs[exp] = result.coeffs.get(exp,0) - c
        return result

    def __mul__(self, other):
        assert type(other) is Polynomial
        result = Polynomial(0)
        for exp1,c1 in self.coeffs.items():
            for exp2,c2 in other.coeffs.items():
                result.coeffs[exp1+exp2] = result.coeffs.get(exp1+exp2,0) + c1*c2
        return result
        
    def __representation__(self):
        return "Polynomial" + str(self.coeffs)   

    def __str__(self):
        result = [""]+[f"{c}x^{i}" for i,c in sorted(self.coeffs.items()) if c]+[""]
        result = "+".join(reversed(result))
        result = result.replace("+1x","+x")
        result = result.replace("-1x","-x")
        result = result.replace("x^0","")
        result = result.replace("x^1+","x+")
        result = result.replace("+-","-")
        result = result.strip("+")
        result = result.replace("+"," + ")
        result = result[:1]+result[1:].replace("-"," - ")
        return result.strip()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM