class StackQueue: """ Implementation of Queue using two Stacks. """ def __init__(self, limit=10): self.limit = limit self.stack_one = Stack(limit) self.stack_two = Stack(limit) def enqueue(self, item): if self.isFull(): raise QueueOverflowError("Cannot insert item in a full queue.") self.stack_one.push(item) def _move_item_to_second_stack(self): if self.stack_two.is_empty(): while not self.stack_one.is_empty(): self.stack_two.push(self.stack_one.pop()) def dequeue(self): if self.isEmpty(): raise QueueUnderflowError( "Cannot Remove an item from empty Queue.") self._move_item_to_second_stack() return self.stack_two.pop() def peek(self): self._move_item_to_second_stack() return self.stack_two.peek() def isEmpty(self): return self.stack_one.is_empty() and self.stack_two.is_empty() def isFull(self): return (self.stack_one.size() + self.stack_two.size()) >= self.limit
def infix_to_postfix(infix_expr): prec = {} prec["*"] = 3 prec["/"] = 3 prec["+"] = 2 prec["-"] = 2 prec["("] = 1 op_stack = Stack() postfix_list = [] token_list = infix_expr.split() for token in token_list: if token in "ABCDEFGHIJKLMNOPQRSTUWXYZ" or token in "0123456789": postfix_list.append(token) elif token == '(': op_stack.push(token) elif token == ')': top_token = op_stack.pop() while top_token != '(': postfix_list.append(top_token) top_token = op_stack.pop() else: while (not op_stack.is_empty()) and \ (prec[op_stack.peek()] >= prec[token]): postfix_list.append(op_stack.pop()) op_stack.push(token) while not op_stack.is_empty(): postfix_list.append(op_stack.pop()) return " ".join(postfix_list)