Wednesday, March 15, 2017

Evaluating an expression

Leaving a note to myself - a simple algorithm for evaluating expressions, no unary operators or parentheses.
phase 1 (tokenizer)

'+' => op1, add
'-' => op1, sub
'*' => op2, mul
'/' => op2, div
\d+ => number, value

phase 2 (evaluator)

tuple = first (number, op2, number)
while tuple:
  replace tuple with result of op2

tuple = first (number, op1, number)
while tuple:
  replace tuple with result of op1

there should be a single item left, a number; return its value

No comments: