1. Code does not check for malformed expressions.
2. Operators recognised are +,-,*,/.
3. Unary positive and negative operators are not supported.
Java:
public class PostfixEvaluator {
public int evaluate(String postfixExpression) {
LinkedList<Integer> stack = new LinkedList<Integer>();
char[] chars = postfixExpression.toCharArray();
for (char chr : chars) {
if (isLetter(chr)) {
stack.add(Integer.valueOf(String.valueOf(chr)));
} else {
int no1 = stack.removeLast();
int no2 = stack.removeLast();
stack.add(perfromMathematicalOperation(no2, no1, chr));
}
}
return stack.removeLast();
}
public static boolean isLetter(char chr) {
try {
Integer.parseInt(String.valueOf(chr));
return true;
} catch (NumberFormatException nfe) {
return false;
}
}
public int perfromMathematicalOperation(int a, int b, char operator) {
switch (operator) {
case '+':
return a + b;
case '-':
return a - b;
case '*':
return a * b;
case '/':
return a / b;
default:
throw new AssertionError("Invalid operator : " + operator);
}
}
public static void main(String[] args) {
PostfixEvaluator postfixEvaluator = new PostfixEvaluator();
System.out.println(postfixEvaluator.evaluate("34-5+"));
}
}
Python:
import operator
operator_functions = {
'+': operator.add,
'-': operator.sub,
'*': operator.mul,
'/': operator.div
}
postfix_expression = "34-5+"
stack = []
for char in postfix_expression :
if char in operator_functions:
no1 = int(stack.pop())
no2 = int(stack.pop())
stack.append(operator_functions[char](no2, no1))
else :
stack.append(char)
print stack.pop()
Question I asked in stackoverflow regarding this code.