[Edu-sig] Polynomial object (trimmed down)

Kirby Urner urnerk@qwest.net
Tue, 10 Jun 2003 18:06:28 -0700


I've posted re a Polynomial object here before, but the trimmed-down
one below I like for its streamlined multiplication method.  Check
usage examples.

This is an excerpt from a couple of my PowerPoint slides for OSCON,
which were due today, for my presentation 'Python in Education'.
I did a dry run for a patient and helpful PORPIG audience last night
(that's the Portland Python Interest Group) and it seemed to go
pretty well.  I learned not to say "Pahvray" for POV-Ray though
-- a long time ray tracer was in attendance.  It's "Pee Oh Vee Ray".

class Poly (object):

     def __init__ (self,coeffs):
         self.coeffs = coeffs

     def __call__ (self,x):
	 return sum([b*x**i
                     for i,b in enumerate(self.coeffs)])

     def __repr__ (self):
	 r = ' + '.join(["(%s * x**%s)" % (b,i) for
                 i,b in enumerate(self.coeffs) if b<>0])
         return r.replace(' * x**0','')

     def __mul__ (self, other):
         outerp = [( e1+e2, c1*c2 )
                        for e1,c1 in enumerate(self.coeffs)
                        for e2,c2 in enumerate(other.coeffs)]
         sums = {} # add like terms in dictionary
         for t in outerp:
              sums[t[0]] = sums.get(t[0],0) + t[1]
         return Poly([sums[i] for i in range(len(sums))])

 >>> from pyedu import *
 >>> p = Poly([1,2,3,4])
 >>> s = Poly([1,0,2,0,5])
 >>> p
(1) + (2 * x**1) + (3 * x**2) + (4 * x**3)
 >>> s
(1) + (2 * x**2) + (5 * x**4)
 >>> s*p
(1) + (2 * x**1) + (5 * x**2) + (8 * x**3) + (11 * x**4) +
(18 * x**5) + (15 * x**6) + (20 * x**7)

Kirby