0

目前正在研究一个类,以根据分配在 python 中使用多项式进行算术运算。我了解算术和代码将如何工作,但我之前没有使用过类,我不知道变量如何传入和传出类......特别是当你想传入说......两个多项式并返回一个函数。

我已经插入了一个函数(并希望将其重新组合到一个方法中)我过去曾用来乘以一个多项式(具有相同的基数,我必须根据应用程序的需要对其进行修改)

有人可以告诉我想要输入 2 个多边形然后将它们相乘的语法吗?在线视频不是很有帮助,我可以使用一步一步的解释来解释正在发生的事情。这主要是一个语法问题,代码处于非常早期(和损坏)的阶段。

干杯,D

编辑:我希望采用这种格式的多项式形式。intPoly([2,4,1,2], z) 真的是 2z^3+4z^2+z+2

class IntPoly:
    def __init__(build,length,var):
        build.length = length
        build.var = var

    def addPoly:

    def multiply(a, b):
        a.reverse()
        b.reverse()
        c=[0 for x in range(len(a)+len(b)-1)]

        for i in range (len(a)):
            for j in range (len(b)):
                k = a[i]*b[j]
                ii=i+j
                c[ii]+=k

        c.reverse()

        return (c)

    def equalTo:

    def deg:

    def itterate:

    def printReal:
4

2 回答 2

0

您可以将它们传递给构造函数。这就是我认为您正在寻找的内容:

class IntPoly(object):
    def __init__(self, poly1, poly2):
        self.poly1 = poly1
        self.poly2 = poly2

    def multiply():
        """Here you would do your proper conversion and parsing
        given the representation of the polynomials.
        But pretending that they are just numbers, you would do the following:"""
        return self.poly1 * self.poly2

你会创建一个这样的对象,并且可以使用 multiply 方法来获得产品:

myPolyObject = IntPoly([4, 3, 2], [1, 2, 3])
print myPolyObject.multiply()          

如果您需要考虑任意数量的多项式,我们称之为n多项式,那么您可以简单地将它们全部保存在一个列表中。

class IntPoly(object):
    def __init__(self, poly_list):
        self.poly_list = poly_list

    def multiply():
        """Here you would do your proper conversion and parsing
        given the representation of the polynomials.
        But pretending that they are just numbers, you would do the following:"""
        return reduce(lambda x,y: x*y, self.poly_list)

myPolyObject = IntPoly([[4, 3, 2], [1, 2, 3], [4, 7, 8]])
print myPolyObject.multiply()

reduce函数基本上采用一个函数并将其应用于列表的每个元素,并收集结果。所以,reduce(lambda: x,y: x*y, [1, 2, 3])会导致计算((1*2)*3))

于 2014-10-26T15:26:43.313 回答
0
class Poly():
    """DocString"""
    def __init__(self, loc):
        self.loc = loc
        self.degree = len(loc)
        ...
    ## __add__ is a standard method name, google for python __add__
    def __add__(self, poly2):
        loc1 = self.loc
        loc2 = poly2.loc
        # do stuff and compute loc3, list of coefficients for p1+p2
        return Poly(loc3)
    def __mul__ ...

p1 = Poly([4,3,2,1])
p2 = Poly([3,4,0,0])
p3 = p1+p2

如果您想要print多项式,请阅读标准方法__repr__以及__str__python 用于打印或表示自定义对象的方法。如果您不关心使用能力,print您可以随时访问实例的成员

print "Degree of sum", p3.degree
print "List of coefficients of sum", p3.loc
于 2014-10-26T16:30:34.577 回答