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.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Because python supports some algebraic forms, you could do:
But this allows the input to execute about anything defined in your env:
Also, if you want to support something python doesn’t support, the approach fails:
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.