Teifion
Teifion

Reputation: 110989

Reading and running a mathematical expression in Python

Using Python, how would I go about reading in (be from a string, file or url) a mathematical expression (1 + 1 is a good start) and executing it?

Aside from grabbing a string, file or url I have no idea of where to start with this.

Upvotes: 5

Views: 4980

Answers (6)

Philippe F
Philippe F

Reputation: 12165

You can take advantage of Python's own evaluation capabilities. However, blind use of eval() is a very dangerous, since somebody can trick your program into:

eval( (__import__("os").system("rm important_file") or 1) + 1)

The correct way to use eval is with the following receipe, which will make sure nothing dangerous is contained in the expression that you are evaluating:

http://code.activestate.com/recipes/496746-restricted-safe-eval/

Upvotes: 0

technomalogical
technomalogical

Reputation: 3002

Don't writing your own parser unless you want to learn how to write a parser. As already mentioned in the comments by @J.F. Sebastian, I would suggest a full-on computer algebra system (CAS) like SAGE. It will handle mathematical statements much more complicated than 1+1 :)

Upvotes: 2

Cheery
Cheery

Reputation: 25433

Because python supports some algebraic forms, you could do:

eval("1 + 1")

But this allows the input to execute about anything defined in your env:

eval("__import__('sys').exit(1)")

Also, if you want to support something python doesn't support, the approach fails:

x³ + y² + c
----------- = 0
     z

Instead of doing this, you can implement a tokenizer and a parser with ply. Evaluating a thing like '1 + 1' ought not take more than ten lines or so.

You could also implement the tokenizer and the parser by hand. Read about LL and LR parsers. Before attempting this it's also better to learn using parser generators first.

Upvotes: 7

S.Lott
S.Lott

Reputation: 391852

Read about the input function.

Upvotes: 1

Alex Coventry
Alex Coventry

Reputation: 70867

Perhaps eval is what you're after?

>>> eval('1+1')
2

Upvotes: 1

Simon
Simon

Reputation: 80769

If you are receiving an expression as a string you'll need to parse it into its operators and operands and then process the resulting tree. This isn't a python problem per se. but a general issue of how to deal with mathematical expressions delivered as strings.

A quick google reveals a bunch of lexical parsers for python.

Upvotes: 2

Related Questions