[Tutor] Input to python executable code and design question

jfouhy at paradise.net.nz jfouhy at paradise.net.nz
Mon Jan 10 02:14:15 CET 2005


Quoting Ismael Garrido <ismaelgf at adinet.com.uy>:

> (Newbie looking scared) That's kind of hard for me... Parsing it myself
> is too complex for me. Also, I hoped Python's math would do the job for
> me, so I wouldn't have to make what's already done in Python.

Writing  (and understanding) grammar is probably easier than you think --- once
you get over the syntax.  And they are fantastically useful things for doing any
sort of parsing.  But no matter..
 
> For what I understood of Mr. Clarke's mail, eval() would do the job (in
> spite of the security problem, I'm not concerned about that). Is that 
> correct? I guess I'll go read about that a bit more.

Yeah, probably.  For example:

>>> from math import *
>>> x = 3
>>> y = 2
>>> eval("2*x + 3*sin(x + y)")
3.1232271760105847

Note that if I had done "import math" instead of "from math import *", it would
not have worked, because "sin" would not have been defined.

So you could do something like:

def evalAt(function, x):
   """ Evaluate a function (as a string) at a given point. """
   return eval(function)
# This is equivalent to: evalAt = lambda function, x: eval(function)

myFun = "2*x + 3*sin(x + y)"
evalFunction = lambda x: evalAt(myFun, x)
xPoints = [x / 10000.0 for x in xrange(10000)]
yPoints = map(evalFunction, xPoints)

One problem with this approach is that you are required to use 'x' as the
variable when you are typing in your function.

Oh, to answer your other question: It is almost certainly better to calculate
the points first, and then plot them.

-- 
John.


More information about the Tutor mailing list