[Tutor] Input to python executable code and design question
jfouhy at paradise.net.nz
jfouhy at paradise.net.nz
Mon Jan 10 00:52:24 CET 2005
Quoting Ismael Garrido <ismaelgf at adinet.com.uy>:
> I am trying to make a program that will plot functions. For that, I need
> to be able to get an input (the function to be plotted) and execute it.
> So, my question is, how do I use the input? I have found no way to
> convert the string to some kind of executable code.
So you want the user to be able to type something like "f(x) = sin(2*x)" and
then your program will plot it --- is that correct?
Maybe you could parse it yourself? I have found SimpleParse quite easy to use
--- http://simpleparse.sourceforge.net/ . You will need to write your own
grammar to describe functions --- something like this, I guess:
eqn := fname, '(', varlist, ')=', expr
varlist := var, (',', var)*
expr := atom, (binop, atom)?
atom := var / (fun, '(', expr, ')') / num
fun := 'sin' / 'cos' / 'tan' / ...
var := char
fname := char+
num := digit+
binop := '+' / '*' / '/' / '-'
char := [a-zA-Z]
digit := [0-9]
although you will need to work on that to get the precedence right and avoid
undesired recursion and the like. SimpleParse will give you a tree (made of
nested tuples) representing your function. You can then have a go at converting
the tree to a function.
I guess the standard way to do this would be something like:
def convert(node):
functionName = node[0]
children = node[1]
if functionName == '*':
return convert(children[0]) * convert(children[1])
elif functionName == '+':
...
But you may be able to come up with something more clever.
Hope this helps.
--
John.
More information about the Tutor
mailing list