>>> import this
... though rules are made to be broken
11–20 of 34 posts
>>> import this
... though rules are made to be broken
Very cool. Thanks for the cool post. I am not sure I got the difference between the LL and LR parser. Is what you have above an LR parser? Also, why did you choose to represent both + and - as "ADD" tokens (and * and / as "MUL") is this to enforce evaluation priority? It would be interesting to see if you can add or ^ as an exponent for this calculator. Maybe you intended this post strictly as as an educational post,…
An LL-parser tries to expand the initial rule into a more complex rule structure, until it matches the input. So to match a+b+c+d it will do [start] -> [add] -> [add] + [num] -> [add] + [num] + [num] -> etc.
What I wrote is an LL-parser, simply because it's much much simpler to write and to understand.
Yes, both ADD and MUL are used for precedence. Since any list of +- or of */ will evaluate correctly if reduced from left to right, I didn't mind grouping them together and making my life easier (and shorter).
It was strictly educational, and also a shtick; a short code hack. If I was to write an actual parser (and I don't think I would ever try to), it would look very different!
This article seems rather un-Zen >>> import this ... though rules are made to be broken
I wonder if there's a way to add algebraic equation solving to this, or something like it, easily.
from sympy import *
var('x,b,c')
print solve(a*x**2+b*x+c,x)
Result: [(-b + (-4*a*c + b**2)**(1/2))/(2*a), -(b + (-4*a*c + b**2)**(1/2))/(2*a)]How to Write a Calculator in 1 Python Line print input() > 25*4-50 > 50
A. I don't need to; other people will write it for me.
That's fine, I guess. I prefer to understand.
This article seems rather un-Zen >>> import this ... though rules are made to be broken
Why is it un-zen?
Then you wouldn't be too far from Norvig's little educational gems.
Earlier quoted context omitted.
Why is it un-zen?
I think it is not too unzen in its aim and method but if you ask there many little tricks that I'd say are unzen. First, give all the code a pass of autopep8 comb. Second, avoid things like "lambda (op,num): (num, -num)[...], just use "x if y else z" Then you wouldn't be too far from Norvig's little educational gems.
Thank you, you gave me a great compliment. Norvig's short spellchecker was very inspirational for me.