Eep.
On Mon, 10 Jan 2005 13:04:33 +1300, Liam Clarke <[EMAIL PROTECTED]> wrote: > I think you're looking for eval() - but that's a big security hole, > and wouldn't handle f(x) notation overly well, unless you parse like > John said. > > > On Mon, 10 Jan 2005 12:52:24 +1300 (NZDT), [EMAIL PROTECTED] > <[EMAIL PROTECTED]> wrote: > > Quoting Ismael Garrido <[EMAIL PROTECTED]>: > > > > > 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. > > _______________________________________________ > > Tutor maillist - [email protected] > > http://mail.python.org/mailman/listinfo/tutor > > > > > -- > 'There is only one basic human right, and that is to do as you damn well > please. > And with it comes the only basic human duty, to take the consequences. > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. _______________________________________________ Tutor maillist - [email protected] http://mail.python.org/mailman/listinfo/tutor
