Velocity Reviews > Re: Turning a string into an programatic mathematical expression

# Re: Turning a string into an programatic mathematical expression

John Hunter
Guest
Posts: n/a

 10-20-2004
>>>>> "Daniel" == Daniel Bickett <(E-Mail Removed)> writes:

Daniel> The title really says it all. I'm trying to take input
Daniel> from a user (intended to be a mathematical expression),
Daniel> from a text box for example, and evaluate it
Daniel> mathematically within the program. For clarification: the
Daniel> user inputs the string "4*5(3-3)", I would be interested
Daniel> in a straight-forward way to find the result of that,
Daniel> based only on a string. The follow-up question would be
Daniel> how to incorporate variables into the mix, however I'll
Daniel> leave it at that for now. Thanks for your time

Depending on what sort of grammar you want to require for input
strings, it can be as simple as

>>> s = "4*5*(3-3)"
>>> eval(s)

0

Although it may not appear so at first glance, I think you are
describing a proposed solution to your problem and not the problem you
are really trying to solve. If you restate the problem you are trying
you're on the road to writing a mathematical expression parser. Note
that python has an expression parser built in, and it gives you access
to that parser in http://www.python.org/doc/current/li...e-parser.html;,
by reusing the python parser you may save yourself some labor.

If you are interested in numeric rather than symbolic processing of
the mathematical expressions, the weave module, via blitz expression
templates, does something quite close. You give it strings like
'a*(b+c)' where a, b and c are numeric arrays, and it will use blitz
expression templates to process this in a single loop without the
creation of temporaries and multiple loops that such expressions
generally entail - www.scipy.org/documentation/weave .

The book "Scientific and Engineering C++" by Barton and Nackman
describes how to implement a mathematical expression parser that
supports variables, binary operations, etc.

JDH