[Tutor] Polynomial class (a beginning)

Kirby Urner urnerk@qwest.net
Wed, 23 Jan 2002 14:24:21 -0800


 >>> class Poly:
	def __init__(self,coeffs):
	    self.coeffs = coeffs
	    self.degree = len(self.coeffs)-1
	def __repr__(self):
	    outstr = ""
	    terms = ["+(("+str(self.coeffs[k])+")*x**"+str(self.degree-k)+")" \
	             for k in range(len(self.coeffs)) \
	             if self.coeffs[k]<>0]
	    outstr = reduce(add,terms)
	    return outstr
	def __call__(self,val):	
	    return apply(eval("lambda x:" + self.__repr__()), (val,))

	
 >>> p = Poly([1,2,3])  # enter coefficients of x powers
 >>> p                  # get back a string representation (kinda messy)
+((1)*x**2)+((2)*x**1)+((3)*x**0)
 >>> p(3)               # the string may be evaluated for x = number
18

Possible next methods:

Add two polynomials to get a polynomial
Multiply two polynomials, making some use of already-defined add


Kirby