Lecture Notes on 18 Oct 2023 class Stack (object): def __init__(self): self.stack = [] # add an item to 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)) class Queue (object): def __init__ (self): self.queue = [] # add an item to the end of the queue def enqueue (self, item): self.queue.append (item) # remove an item from the beginning of the queue def dequeue (self): return (self.queue.pop(0)) # check if the queue is empty def is_empty (self): return (len (self.queue) == 0) # return the number of elements in the queue def size (self): return (len (self.queue)) * Polish notation was invented by Jan Lucasiewicz in 1920. In the 1950s australian computer scientist Charles Hamblin suggested placing the operator after the operands which defined the reverse polish notation. * Evaluate the following RPN expressions: 4 8 7 + 2 * 3 1 - * + 3 4 + 5 * 3 4 5 + * 7 4 + 3 - 2 5 * / * Some definitions for the Reverse Polish Notation 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