+ 1
How's my python Parser?
I just published one on my profile. Took me roughly an hour or so to make. Any feedback is much appreciated. It takes a string that's formatted as a mathematical equation ("5+5/2*9") and solves it using the order of operations. The only limitation is that it won't accept parentheses.
4 Answers
+ 2
1. It takes only single digit numbers. This is easy to fund in the 1st function where you break your string. you could really check if current & prev items are digits and add them (prev = prev * 10 + new) to form a number.
2. It doesn't really obey the correct operator precedence. try "4*5/2*4" and you will get 2.5 instead of 40.
The easiest way to write a real parser is to define a BNF (google this, "backus naur form"), and implement it using recursion.
+ 2
Not too shabby!
The code for your four operations (+-*/) looks very similar though, you should try and abstract that out. (lambdas!)
The program also crashes on "3--3" :P
+ 1
It'll now notice if you put too many operators in the equation (like "3--3") and fix the problem @schin. I forgot about that. I noticed the code being repeated frequently earlier. I'm hoping to solve it later with a reference variable and a function.
It'll also accept more than one digit now @udi. I forgot about including more than one digit too. The issue with operator precedence has been fixed. I'll look into BNF.
Thanks for the feedback.
0
instead of recursion or backus-naur form (how do you implement a language descriptor using recursion, Udi? :P), you should learn what Tokenisation is and an Abstract Syntax Tree. It's easy to implement in Python. I did it myself in a couple days.