[Edu-sig] Algebra + Python
Brent Burley
Brent.Burley@disney.com
Mon, 30 Apr 2001 09:56:49 -0700
Kirby wrote:
> There may be a better way to write the factory function than
> I've shown below. I'd like to see other solutions:
>
> >>> def makepoly(A,B,C):
> """
> Build a polynomial function from coefficients
> """
> return eval("lambda x: %s*x**2 + %s*x + %s" % (A,B,C))
How about this?
class poly:
def __init__(self, A, B, C):
self.A, self.B, self.C = A, B, C
def __call__(self, x):
return self.A * x**2 + self.B * x + self.C
>>> f = poly(2,3,4)
>>> f(10)
234
Having to know about classes pushes you more into learning Python as a
programming language rather than just using Python as a math exploration
tool, but that could be a good thing. You could even expand on the idea
by adding additional methods that relate to polynomials (deriv,
integral, roots, etc.):
class poly:
...
def deriv(self, x):
return 2*self.A*x + self.B
>>> f.deriv(2)
11
Brent