def test_peek_shows_top_of_2_item_stack(self): test_obj = Stack() test_data1 = 'data1' test_data2 = 'data2' test_obj.push(test_data1) test_obj.push(test_data2) self.assertEqual(test_data2, test_obj.peek()) self.assertEqual(False, test_obj.is_empty()) self.assertEqual(test_data2, test_obj.peek())
def test_peek_single_item(self): value1 = 5 my_stack = Stack() my_stack.push(value1) peeked_item = my_stack.peek() self.assertEqual(1, my_stack.count) self.assertEqual(5, peeked_item)
def infix_to_postfix(infix_exp): prec = {} prec["*"] = 3 prec["/"] = 3 prec["+"] = 2 prec["-"] = 2 prec["("] = 1 op_stack = Stack() postfix_list = [] token_list = infix_exp.split() for token in token_list: if token in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" or token in "1234567890": postfix_list.append(token) elif token == '(': op_stack.push(token) elif token == ')': top_token = op_stack.pop() while 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)
def test_peek(): s = Stack() s.push("apple") s.push("banana") actual = s.peek() expected = "banana" assert actual == expected
def test_peek_multiple_items(self): value1, value2, value3 = 5, 8, 11 my_stack = Stack() my_stack.push(value1) my_stack.push(value2) my_stack.push(value3) peeked_item = my_stack.peek() self.assertEqual(3, my_stack.count) self.assertEqual(11, peeked_item)
def generateMaze(nodes): nodes.getEmptyGrid() index = randint(0, len(nodes.nodeList)-1) nodeEnd = nodes.nodeList[index] nodeEnd.visited = True allNodesVisited = False #print "start = " + str(index) stack = Stack() while not allNodesVisited: unvisitedNodes = nodes.getUnvisitedNodes() index = randint(0, len(unvisitedNodes)-1) nodeStart = unvisitedNodes[index] endFound = False stack.push(nodeStart) while not endFound: directionList = nodes.getDirections(stack.peek()) directionIndex = randint(0, len(directionList)-1) direction = directionList[directionIndex] nodeNext = nodes.getUnlinkedNode(stack.peek(), direction) if not nodeNext.visited: if stack.contains(nodeNext): while stack.peek() is not nodeNext: stack.pop() else: stack.push(nodeNext) else: #Carve out the path that is defined by the stack stack.push(nodeNext) endFound = True while not stack.isEmpty(): node1 = stack.pop() node2 = stack.peek() node1.visited = True if node2 is not None: #print node1, node2 direction = nodes.getDirectionFromNodes(node1, node2) nodes.addPath(node1, direction) else: stack.clear() unvisitedNodes = nodes.getUnvisitedNodes() if len(unvisitedNodes) == 0: allNodesVisited = True
def sortAscendingOrder(s1): s2 = Stack() while not s1.isEmpty(): # print 'S2:', s2.stack() # print 'S1:', s1.stack() last = s1.pop() while (not s2.isEmpty() and s2.peek() > last): s1.push(s2.pop()) s2.push(last) return s2
class MaxStack: def __init__(self): self.stack = Stack() self.largest = Stack() def push(self, item): self.stack.push(item) if item >= self.largest.peek(): self.largest.push(item) def pop(self): item = self.stack.pop() if item == self.largest.peek(): self.largest.pop() return item def get_largest(self): return self.largest.peek()
def deciToBin(num): binaryStack = Stack() binNum = "" print(f"The binary of {num} is: ", end="") while num > 0: binaryStack.push(num % 2) num = num // 2 while not (binaryStack.isEmpty()): binNum += str(binaryStack.peek()) binaryStack.pop() print(binNum)
class MyStackQueue: def __init__(self, data): self.in_stack = Stack() self.out_stack = Stack() self.first = None self.last = None def add(self, data): self.in_stack.push(data) def remove(self): if not self.out_stack.is_empty(): return self.out_stack.pop() self._shift_between_stacks() if not self.out_stack.is_empty(): return self.out_stack.pop() else: return None def peek(self): if not self.out_stack.is_empty(): return self.out_stack.peek() self._shift_between_stacks() if not self.out_stack.is_empty(): return self.out_stack.peek() else: return None def is_empty(self): return self.out_stack.is_empty() and self.in_stack.is_empty() def _shift_between_stacks(self): #Move all elements from in_stack to out_stack, #then pop from out_stack. while not self.in_stack.is_empty(): self.out_stack.push(self.in_stack.pop())
class minStack(Stack): def __init__(self): super(minStack,self).__init__() self.minSta = Stack() def pop(self): if self.minSta.peek() != None and self.minSta.peek() >= self.peek(): self.minSta.pop() return super(minStack, self).pop() def push(self, data): if self.minSta.peek() == None or self.minSta.peek() >= data: self.minSta.push(data) super(minStack, self).push(data) def peek(self): return super(minStack, self).peek() def min(self): return self.minSta.peek()
def generateMaze(nodes): nodes.getEmptyGrid() index = randint(0, len(nodes.nodeList)-1) node = nodes.nodeList[index] node.visited = True allNodesVisited = False #print "start = " + str(node.row) + ", " + str(node.column) stack = Stack() #unvisitedNeighbors = nodes.getUnvisitedNeighbors(node) #print len(unvisitedNeighbors) stack.push(node) while not stack.isEmpty(): unvisitedNeighbors = nodes.getUnvisitedNeighbors(stack.peek()) #print "Unvisited Neighbors = " + str(len(unvisitedNeighbors)) if len(unvisitedNeighbors) > 0: index = randint(0, len(unvisitedNeighbors)-1) nodeNext = unvisitedNeighbors[index] direction = nodes.getDirectionFromNodes(stack.peek(), nodeNext) nodes.addPath(stack.peek(), direction) nodeNext.visited = True stack.push(nodeNext) else: stack.pop()
def sort_stack(stack): if stack.is_empty(): return stack temp = Stack() while not stack.is_empty(): if temp.is_empty(): temp.push(stack.pop()) else: val = stack.pop() while not temp.is_empty() and temp.peek() > val: stack.push(temp.pop()) temp.push(val) while not temp.is_empty(): stack.push(temp.pop())
def infixToPostfix(infixexpr): from stacks import Stack from string import digits, ascii_uppercase print(infixexpr) infixexpr = infixexpr.replace('**', '^') print(infixexpr) tokenList = ''.join( [' ' + x + ' ' if not x in digits else x for x in infixexpr]) tokenList = tokenList.split() print(tokenList) prec = {} prec['^'] = 4 prec['*'] = 3 prec['/'] = 3 prec['+'] = 2 prec['-'] = 2 prec['('] = 1 postfixList = [] opStack = Stack() for token in tokenList: if token in ascii_uppercase or token.isdigit(): postfixList.append(token) elif token == '(': opStack.push(token) elif token == ')': if not opStack.isEmpty(): topStack = opStack.pop() while not opStack.isEmpty() and topStack != '(': postfixList.append(topStack) topStack = opStack.pop() else: while not opStack.isEmpty() and prec[ opStack.peek()] >= prec[token]: postfixList.append(opStack.pop()) opStack.push(token) while not opStack.isEmpty(): postfixList.append(opStack.pop()) result = ' '.join(postfixList) result = result.replace('^', '**') return result
def is_balanced(string): """Check that the paranthesis in a strigng are balanced.""" s = Stack() match_dict = {')': '(', ']': '[', '}': '{'} for char in string: if char in match_dict.values(): s.push(char) elif char in match_dict.keys(): if s.size() == 0: return print('The paranthesis are not balanced') elif s.size() != 0 and char != s.peek(): s.pop() else: pass if s.is_empty(): return print('The paranthesis are balanced')
class Calculator(): def __init__(self): self.operators = Stack() self.operands = Stack() self.operatorsMap = {'/': 2, '*': 2, '-': 1, '+': 1, '(': 0, ')': 0} def evaluate(self, expression): if expression is None or len(expression) == 0: return 0 expression = expression.split(' ') for ch in expression: if self.isOperand(ch): self.operands.push(int(ch)) elif ch == '(': self.operators.push(ch) elif ch == ')': while self.operators.peek() != '(': self.process() self.operators.pop() elif self.isOperator(ch): while not self.operators.empty() and self.precedence( self.operators.peek()) >= self.precedence(ch): self.process() self.operators.push(ch) while not self.operators.empty(): self.process() return self.operands.pop() def process(self): map = {'+': self.add, '-': self.sub, '*': self.multi, '/': self.divide} right = self.operands.pop() left = self.operands.pop() operator = self.operators.pop() func = map[operator] r = func(left, right) self.operands.push(r) def isOperand(self, char): return re.match(r'^\d+$', char) is not None def isOperator(self, char): return char in self.operatorsMap def precedence(self, operator): if operator not in self.operatorsMap: raise Exception(f"unknown operateor {operator}") return self.operatorsMap[operator] def add(self, left, right): return left + right def sub(self, left, right): return left - right def divide(self, left, right): return left / right def multi(self, left, right): return left * right
def test_peek_empty(): s = Stack() with pytest.raises(InvalidOperationError) as e: s.peek() assert str(e.value) == "Method not allowed on empty collection"
def prior(i): if i == '*' or i == '/' or i == '%': return 1 elif i == '+' or i == '-': return 2 elif i == '(': return 3 from stacks import Stack exp = input("Enter an infix expression: ") + ')' op = Stack() postfix = [] op.push('(') for i in exp: if i.isalpha(): postfix.append(i) elif i == '(': op.push(i) elif i == '*' or i == '/' or i == '%' or i == '+' or i == '-': if prior(op.peek()) < prior(i): postfix.append(op.pop()) op.push(i) elif i == ')': while (op.peek() != '('): postfix.append(op.pop()) temp = op.pop() print("The postfix expression is: {}".format("".join(postfix)))
def test_peek_handles_empty_stack(self): test_obj = Stack() self.assertEqual(None, test_obj.peek()) self.assertEqual(True, test_obj.is_empty())
def test_peek_shows_item_in_1_item_stack(self): test_obj = Stack() test_data = 'data1' test_obj.push(test_data) self.assertEqual(test_data, test_obj.peek()) self.assertEqual(False, test_obj.is_empty())
def test_peek_no_item(self): my_stack = Stack() peeked_item = my_stack.peek() self.assertEqual(0, my_stack.count) self.assertEqual(None, peeked_item)