[Edu-sig] enumerate

Kirby Urner urnerk at qwest.net
Mon Dec 15 11:26:16 EST 2003



In addition to 'zip', I like 'enumerate'.

It helps with that polynomial class I was mentioning.  

 >>> def value(plist,x):
      """Evaluate a polynomial with coeffs plist at x"""
	return sum([c*(x**e) for e,c in enumerate(plist)])

 >>> def repr(plist):
      """Takes polynomial coefficients plist and returns
      a formatted textual representation of the poly"""
	terms = ['%s*(x**%s)' % (c,e) for e,c in enumerate(plist) if not
c==0]
	return " + ".join(terms).replace("*(x**0)","")

Using:

 >>> repr([1,0,2,3,-1,5])
 '1 + 2*(x**2) + 3*(x**3) + -1*(x**4) + 5*(x**5)'

 >>> value([1,0,2,3,-1,5],4)
 5089

Another way to check results:

 >>> x = 4
 >>> eval(repr([1,0,2,3,-1,5]))
 5089

Change value to __call__ and repr to __repr__, add some self stuff, and
you've got your little Poly class (still need __add__ and __mul__ tho).

Kirby





More information about the Edu-sig mailing list