[Edu-sig] More Pythonic Precalculus (Python 2.0)

Kirby Urner pdx4d@teleport.com
Mon, 25 Sep 2000 11:05:48 -0700

Not news to long term Pythoneers I'm sure, but a fun puzzle for me,
was how to accept arbitrary algebraic expressions in terms of x 
as text strings, and then have the expression evaluate for any x.

For example:  f(x) = 2x^2 + 3x + 10 (x is Real)
              f(5) = 75

This is the kind of thing school teachers are always looking for -- 
then you wire the back end to a graphing facility so kids can enter 
any function and see what it looks like on the Cartesian plane.

Here's one solution:

 >>> import string
 >>> def mkfunc(rule, x):
	eq = string.join(string.split(rule,"x"),"(%s)")
	return eval(eq % ((x,)*eq.count("%s")))

 >>>  mkfunc("2*x**2 + 3*x + 10",5)

If we print intermediate results, you can see more clearly 
what's going on:

 >>> mkfunc("2*x**2 + 3*x + 10",5)
 2*x**2 + 3*x + 10         # original rule (string)
 2*(%s)**2 + 3*(%s) + 10   # (%s) substituted for every x
 (5, 5)                    # = (x,)*eq.count("%s") 
                           #    need a tuple with as many x's as %s's
 75                        # final result, for x = 5

I've incorporated this result in my camera class at 

Works like this:

 >>> import precalc, from precalc import camera
 >>> mycam = camera("2*x**2 - 4*x + 3",-3,3,0.1)

Where 1st parameter is any rule (as text), then you get start and 
finish values with step or increment (0.1 in this case).

Again, nothing new for long term Pythoneers.  Plus it's always
easy enough to write your function as a def and pass it in as
an object ref -- that's what I do elsewhere in the same module.

As usual, I use Povray for my graphical back end, but have some
Tk stuff ready (less sophisticated than what's already out 
there, e.g. by Grayson) for when 2.0b2 comes out (release