Live data from Hacker News

How To Write A Calculator in 70 Python Lines

blog.erezsh.com

21–30 of 34 posts

Re: How To Write A Calculator in 70 Python Lines

#21
Very nicely done!

I think a precedence parser could be even shorter, though I don't seem to have one handy in Python. Pratt parsing is similar, though: https://github.com/darius/sketchbook/blob/master/parsing/pra... And here's precedence parsing in C: http://wry.me/~darius/hacks/dcalc.c (I learned this method from Dave Gillespie, author of Gnu Calc.)

Finally, using a small parsing library very similar to the scheme in this post: https://github.com/darius/peglet/blob/master/examples/infix....

Re: How To Write A Calculator in 70 Python Lines

#23
post #20

Earlier quoted context omitted.

Mathematically, this is wrong.. a + b is not ab.

It's not symbolic...

Of course. I understand that "a" + "b" when taken to mean "concatenate the strings" is "ab" but OP's post was a calculator. It would not have yielded this result.

Re: How To Write A Calculator in 70 Python Lines

#25
post #16
post #2

How to Write a Calculator in 1 Python Line print input() > 25*4-50 > 50

Q. How to write code? A. I don't need to; other people will write it for me. That's fine, I guess. I prefer to understand.

How to get things done? Use existing tools unless they are not suitable.

Re: How To Write A Calculator in 70 Python Lines

#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.

Re: How To Write A Calculator in 70 Python Lines

#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
Post reply on HN