Practice Exercise: Expression Parsing
21 of March, 2015
Write an evaluator for mathematical expressions. Sample expressions:
Background
The notation, which looks most natural to us and is taught at schools is called infix. In infix operators are written in between of operands. The order of evaluation of operations can be left-to-right or right-to-left. It depends on the order of precedence of operators in expression.
There are two other equivalent notations, called postfix and prefix.
In postfix notation operators are written after operands. The order of evaluation is always the same: left-to-right. Unlike in infix, order of evaluation is fixed. There are no brackets, and no way to override the flow.
In prefix notation operators are written before operands. As in postfix evaluation is always left-to-right and brackets cannot be used to override the flow.
Sample algorithm
The simple way to evaluate infix expression is first to convert it to postfix and then evaluate postfix, which is more strict and easier to implement.
- To convert infix to postfix have a stack for operators and read infix expression from left to right:
- If number: print it out.
- If operator: push to stack until the operator with lower precedence appears. When operator with lower precedence appears, then pop it from stack and print it.
- To evaluate postfix have a stack for numbers and read postfix expression from left to right:
- If number: push to stack.
- If operator:
- Pop top two numbers off the stack (note that they are popped out in reverse order)
- Perform operation on those two numbers.
- Push resulting number to stack.
Sample implementation
My sample implementation is in PHP with PhpSpec. See github repository with full source code.
If you have other implementation - please share in comment.
This exercise is inspired by CS 61B: Data Structures lecture from Berkeley University.
comments powered by Disqus