# L-26 MCS 260 Fri 26 Oct 2007 : class Poly class Poly: "defines a polynomial in one variable" def __init__(self,c=0,p=0): "monomial with coefficient c and power p" if c==0: self.__L = [] else: self.__L = [(c,p)] def addmon(self,c,p): "adds a monomial" if c != 0: done = False for i in range(0,len(self.__L)): m = self.__L[i] if m[1] == p: nc = c + m[0] del(self.__L[i]) if nc != 0: self.__L.append((nc,p)) done = True break if not done: self.__L.append((c,p)) def __add__(self,other): "adds two polynomials" p = Poly() for m in self.__L: p.addmon(m[0],m[1]) for m in other.__L: p.addmon(m[0],m[1]) return p def __str__(self): "returns a polynomial as a string" s = '' for m in self.__L: s += '%+2.f*x^%d' % (m[0],m[1]) if s == '': return '0' else: return s