parsing (priority of continuation): push character out of input result = call nud this character while the lbp priority of the next in the continuation priority symbol stream: push character out of input result = apply the led of this symbol to the current result
operators = { # led '+': [1, lambda left: "(%s + %s)" % (left, parse(1))], '*': [2, lambda left: "(%s * %s)" % (left, parse(2))], '^': [3, lambda left: "(%s ^ %s)" % (left, parse(3))], '$': [0] } def lbp(t): try: return operators[t][0] except KeyError: return 0 def nud(t): return t def led(t,left): return operators[t][1](left) # , . def parse(rbp=0): global tokens tok = tokens.pop(0) result = nud(tok) while lbp(tokens[0]) > rbp: tok = tokens.pop(0) result = led(tok,result) return result def evaluate(expr): global tokens tokens = expr.split(" ") + ['$'] parse()
>>> evaluate("a + b * c ^ d * e + f")
a|+,b,*,c,^,d,*,e,+,f,$
= a
+|b,*,c,^,d,*,e,+,f,$
b|*,c,^,d,*,e,+,f,$
= b
*|c,^,d,*,e,+,f,$
c|^,d,*,e,+,f,$
= c
^|d,*,e,+,f,$
d|*,e,+,f,$
= d
= (c ^ d)
= (b * (c ^ d))
*|e,+,f,$
e|+,f,$
= e
= ((b * (c ^ d)) * e)
= (a + ((b * (c ^ d)) * e))
+|f,$
f|$
= f
= ((a + ((b * (c ^ d)) * e)) + f)
>>>
>>> evaluate("a * b + c ^ d + e * f")
a|*,b,+,c,^,d,+,e,*,f,$
= a
*|b,+,c,^,d,+,e,*,f,$
b|+,c,^,d,+,e,*,f,$
= b
= (a * b)
+|c,^,d,+,e,*,f,$
c|^,d,+,e,*,f,$
= c
^|d,+,e,*,f,$
d|+,e,*,f,$
= d
= (c ^ d)
= ((a * b) + (c ^ d))
+|e,*,f,$
e|*,f,$
= e
*|f,$
f|$
= f
= (e * f)
= (((a * b) + (c ^ d)) + (e * f))
Source: https://habr.com/ru/post/50349/
All Articles