Live data from Hacker News

How To Write A Calculator in 70 Python Lines

blog.erezsh.com

31–34 of 34 posts

Re: How To Write A Calculator in 70 Python Lines

#31
post #27
post #26

The calculator seems to miss the point of recursive descent parsing. The parser should follow naturally from the grammar. As an example, here is a 52 line python calculator: https://gist.github.com/ascv/5022712 The idea isn't to 1-up the OP but rather to showcase the technique of recursive descent parsing. The wikipedia entry for recursive descent parsing also has a very nice example.

Well, to be fair, your calculator seems to miss the point of being a calculator... > 10/2*2 2.5

Clearly a bug. Thanks when I have more time I will fix it. I didn't give much thought to operator precedence, I assumed the user would specify it using parentheses.

The idea is what is important though. Recursive descent parsing uses the functions that correspond to types in the grammar to mutually call each other thus parsing the expression recursively in a descending fashion.

Re: How To Write A Calculator in 70 Python Lines

#33
post #27
post #26

The calculator seems to miss the point of recursive descent parsing. The parser should follow naturally from the grammar. As an example, here is a 52 line python calculator: https://gist.github.com/ascv/5022712 The idea isn't to 1-up the OP but rather to showcase the technique of recursive descent parsing. The wikipedia entry for recursive descent parsing also has a very nice example.

Well, to be fair, your calculator seems to miss the point of being a calculator... > 10/2*2 2.5

I decided to simply add to the description, "use parentheses to specify operator precedence."

Re: How To Write A Calculator in 70 Python Lines

#34
post #30

Here is a similar calculator implemented in 58 languages including in 16 lines of Python code :) http://www.math.bas.bg/bantchev/place/rpn/rpn.impl.html

This is an RPN calculator, which means you can basically execute the input using the token stream directly. TFA shows executing a context free language, which requires parsing, explaining the program being an order of magnitude larger.
Post reply on HN