from pyliststack import Stack import math """ Evaulate an postfix expression.

Precondition: the postfix is a valid postfix expression.
Currently only limited forms of expressions are supported. In particular, the numbers have to be single digit, the operators are limited to +,-,*,/ only.

Postcondition: the value of the expression is returned.

@param postfix a postfix form of an expression. @return the integer value of the expression. """ def evaluate_postfix( expression ): exp_stack = Stack() result = 0 for ch in expression: if is_op( ch ): right = exp_stack.pop() # right operand is always on top of left! left = exp_stack.pop() result = do_op( ch, left, right ) else: # the 'ch' must be an operand result = ord( ch ) - ord( '0' ) # convert it to a digit exp_stack.push( result ) return result def is_op( op ): return op in '+-*/^' def do_op( op, left, right ): r = 0 if op == '+': r = left + right elif op == '-': r = left - right elif op == '*': r = left * right elif op == '/': r = left / right elif op == '^': r = math.pow( left, right ) return r def main(): print( "Hit Enter to end this program." ) postfix = input( "Enter a simple arithmetic expression in postfix form : " ) while not postfix == "": result = evaluate_postFix( postfix ) print( postfix + " ==> " + str( result ) ) postfix = input( "Enter a simple arithmetic expression in postfix form : " ) def test_eval(): expressions = ['23^1-', '23+4*', '56-2*', '34-2^', '89*2-', '82/5+'] result = [7, 20, -2, 1, 70, 9] for i in range( len( result ) ): r = result[ i ] e = expressions[ i ] print( 'result should be ', r ) print( e + ' ==> ' + str( evaluate_postfix( e ) ) ) #main() test_eval()