Lecture Notes on 26 Oct 2020 * Evaluate the following RPN expressions: 4 8 7 + 2 * 3 1 - * + 3 4 + 5 * 3 4 5 + * 7 4 + 3 - 2 5 * / * Reverse Polish Notation Revisited Some definitions operator: + - * / // % ** operand: 2 (integers) or 3.4 (floating point numbers) Infix: 2 + 3 Postfix: 2 3 + Prefix: + 2 3 * There is an inherent ambiguity in infix expressions. What does 2 + 3 * 5 mean? Is it (2 + 3) * 5 or 2 + (3 * 5)? * There is no ambiguity using either postfix or prefix notation. (2 + 3) * 5 = 2 3 + 5 * 2 + (3 * 5) = 2 3 5 * + As you can see the two expressions are different in postfix. * Given a valid RPN expression how do you evaluate it * Parse the RPN expression (go through the expression token by token) * If the token is an operand push the operand on the stack * If the token is an operator - pop the stack twice - apply the operator to those operands - push the result on the stack * When you finish parsing there should be only one number in the stack. Pop the stack. That is your answer. * Code to evaluate RPN expressions stored in a file called rpn.txt class Stack (object): def __init__ (self): self.stack = [] # add an item on the top of the stack def push (self, item): self.stack.append (item) # remove an item from the top of the stack def pop (self): return self.stack.pop() # check the item on the top of the stack def peek (self): return self.stack[-1] # check if the stack is empty def is_empty (self): return (len(self.stack) == 0) # return the number of elements in the stack def size (self): return (len(self.stack)) def operate (oper1, oper2, token): expr = str(oper1) + token + str(oper2) return eval (expr) def rpn (s): theStack = Stack() operators = ['+', '-', '*', '/', '//', '%', '**'] tokens = s.split() for item in tokens: if (item in operators): oper2 = theStack.pop() oper1 = theStack.pop() theStack.push (operate (oper1, oper2, item)) else: theStack.push (item) return theStack.pop() def main(): in_file = open ("rpn.txt", "r") for line in in_file: line = line.strip() value = rpn (line) print (line, " = ", value) in_file.close() main()