def test_pop_empty_stack(): stack = Stack() with pytest.raises(IndexError) as exc: stack.pop() assert str(exc.value) == "pop from empty list"
class ReversePolishNotationConverterState: """ Class to store the state of RPN convert process """ def __init__(self, expression_in_infix_notation: str): """ :param expression_in_infix_notation: string with expression in infix notation """ self.expression_in_infix_notation = Queue_( expression_in_infix_notation) self.expression_in_postfix_notation = ReversePolishNotation() self.stack = Stack() def pop_from_stack_until_opening_bracket(self): """ Help function помогает вытащить все из стека :return: """ el = self.stack.top() while not isinstance(el, OpenBracket): self.expression_in_postfix_notation.put(el) self.stack.top() # выкнуть откр скобку из стека self.stack.pop()
def infix_to_postfix(expression): postfix = [] priority = {'(': 1, '&': 2, '|': 2, '!': 2} operators = Stack() for token in expression: if token in OPERATORS: # Operators are added to the stack, but first the ones with a # higher priority are added to the result: while not operators.is_empty() and priority[token] <= priority[ operators.top()]: postfix.append(operators.pop()) operators.push(token) # Left parenthesis are added to the stack: elif token == '(': operators.push(token) # Operators between parenthesis are added from the stack to the result: elif token == ')': while operators.top() != '(': postfix.append(operators.pop()) operators.pop() # Pop the left parentheses from the stack. # Operands are added to the result: else: postfix.append(token) while not operators.is_empty(): # The remaining operators are added from the stack to the result: postfix.append(operators.pop()) return postfix
def parenthesesChecker(string): """ Parentheses Checker validates the string using stack INPUT --------- string : '(()))' RETURN --------- Flag : False """ temp = Stack(); balanceFlag = False for i in string: if i == "(": temp.push('i') if i == ")": if temp.isEmpty(): balanceFlag = False else: temp.pop(); balanceFlag = True if balanceFlag and temp.isEmpty(): return True else: return False
class MaxStack: def __init__(self, data=None): self.stack = Stack() self.max_stack = Stack() if data is not None: self.push(data) def push(self, data): self.stack.push(data) latest_max = self.max_stack.peek() if latest_max is not None: if latest_max.data[0] >= data: node = self.max_stack.pop() node_data = node.data node_data[1] += 1 self.max_stack.push(node_data) else: self.max_stack.push([data, 1]) else: self.max_stack.push([data, 1]) def pop(self): popped_node = self.stack.pop() latest_max = self.max_stack.peek() if latest_max is not None: node = self.max_stack.pop() node_data = node.data node_data[1] -= 1 if node_data[1] > 0: self.max_stack.push(node_data) return popped_node def max(self): latest_max = self.max_stack.peek() return latest_max.data[0]
class QueueOutOfStack: """Implements queue of two stacks. Idea: 1st stack for input, 2nd for output. While enqueue is called, data is stored in the input stack Once dequeue is called it gets data from the output stack until it's empty. If dequeue is called on empty output stack, all data from input stack is flush to the output stack. """ def __init__(self): self.input_stack = Stack() self.output_stack = Stack() def is_empty(self): return self.input_stack.is_empty() and self.output_stack.is_empty() def enqueue(self, item): self.input_stack.push(item) def dequeue(self): if self.output_stack.is_empty(): while not self.input_stack.is_empty(): self.output_stack.push(self.input_stack.pop()) return self.output_stack.pop()
def is_parentheses_balanced(input_string: str) -> bool: """Checks a string for balanced brackets of 3 different kinds: (),{},[]. Args: input_string: a string to be checked Returns: True if parenthesis are balanced, False in other case """ if input_string is None or not isinstance(input_string, str): raise ValueError('Incorrect input parameter! Shall be string') brackets_stack = Stack() par_dict = {'}': '{', ')': '(', ']': '['} for char in input_string: if char in par_dict.values(): brackets_stack.push(char) elif char in par_dict.keys(): last_element = brackets_stack.peek() if last_element == par_dict[char]: brackets_stack.pop() else: return False else: continue return brackets_stack.is_empty()
class QueueStack: def __init__(self): self._stack1 = Stack() self._stack2 = Stack() def enqueue(self, item): """Add item to the enqueue stack. Parameters: item: item to add to the queue """ while len(self._stack1) > 0: self._stack2.push(self._stack1.pop()) self._stack2.push(item) def dequeue(self): """Remove item from the queue. Returns: item: First item in queue """ while len(self._stack2) > 0: self._stack1.push(self._stack2.pop()) return self._stack1.pop()
class Queue: def __init__(self): self._data_stack = Stack() self._utility_stack = Stack() # Complexity: 2 * O(n)?? for 2 for loops, but not nested! def enqueue(self, item): if self._data_stack.__len__() < 1: self._data_stack.push(item) return for _ in range( self._data_stack.__len__() ): # "_" instead of an i variable means you don't care about the variable (saves memory) popped_item = self._data_stack.pop() self._utility_stack.push(popped_item) self._data_stack.push(item) for _ in range(self._utility_stack.__len__()): self._data_stack.push(self._utility_stack.pop()) #everything is on the data stack in the original order # Complexity: O(1) def dequeue(self): if self._data_stack.__len__() < 1: raise Exception("queue is empty") return self._data_stack.pop() # pop removes the data item that's been there the longest, when in a queue def __len__(self): return len(self._data_stack)
def test_pop_error(self): my_stack = Stack() my_stack.push(1) my_stack.push(2) my_stack.pop() my_stack.pop() self.assertRaises(Exception, my_stack.pop)
def test_stack(): stack = Stack() stack.push("foo") stack.push("bar") stack.push("baz") assert "baz" == stack.pop() assert "bar" == stack.pop() assert "foo" == stack.pop()
def test_pop_until_empty(): s = Stack() s.push("apple") s.push("banana") s.push("cucumber") s.pop() s.pop() s.pop() actual = s.is_empty() expected = True assert actual == expected
def test_init(self): stack = Stack([6, 8, 45, 1, 84, 149, 9, 17]) self.assertEqual(stack.pop(), 17) self.assertEqual(stack.pop(), 9) self.assertEqual(stack.pop(), 149) self.assertEqual(stack.pop(), 84) self.assertEqual(stack.pop(), 1) self.assertEqual(stack.pop(), 45) self.assertEqual(stack.pop(), 8) self.assertEqual(stack.pop(), 6)
class QueueOfStacks(object): """A Queue using only Stacks as its underlying data stucture.""" def __init__(self): """Initialize the Queue with two stacks holding data.""" self._out_stack = Stack() self._in_stack = Stack() self._size = 0 def enqueue(self, val): """Add an item to the Queue.""" self._in_stack.push(val) self._size += 1 def dequeue(self): """Remove the front item in the Queue and return it.""" try: item = self._pop() self._size -= 1 return item except IndexError: raise IndexError("Cannot dequeue from an empty Queue.") def peek(self): """Return the front item in the Queue without removing it.""" try: item = self._pop() self._out_stack.push(item) return item except IndexError: return None def size(self): """Return the length of the Queue.""" return self._size def _pop(self): """Pop item from out stack, transferring or raising error if needed.""" try: item = self._out_stack.pop() except IndexError: self._transfer() item = self._out_stack.pop() return item def _transfer(self): """Transfer all items from the from_stack to the to_stack.""" while True: try: self._out_stack.push(self._in_stack.pop()) except IndexError: break
def test_pop(): stk = Stack(0) with pytest.raises(IndexError): stk.pop() stk = Stack(3) stk.push(1) stk.push(2) stk.push(3) stk.pop() stk.pop() assert stk.head.data == 1 assert stk.length == 1
def all_nearest_smaller_values_v2(a): """Compute all nearest smaller values of array a using a Stack.""" r = [] s = Stack() for ix, x in enumerate(a): while not s.is_empty() and s.peek()[1] >= x: s.pop() if s.is_empty(): r.append((None, None)) # (-1, None) else: r.append(s.peek()) s.push((ix, x)) return r
def test_pop_some(): s = Stack() s.push("apple") s.push("banana") s.push("cucumber") s.pop() actual = s.pop() expected = "banana" assert actual == expected
class ReversePolishNotationConverterState: """ Class to store the state of RPN convert process """ def __init__(self, expression_in_infix_notation: str): self.expression_in_infix_notation = Queue_(expression_in_infix_notation) self.expression_in_postfix_notation = ReversePolishNotation() self.stack = Stack() while not ReversePolishNotationConverter.is_open_bracket(self.stack.top()): self.expression_in_postfix_notation.put(self.stack.top()) self.stack.pop() self.stack.pop()
def postfix_calculator(expression: str) -> int: stack = Stack() for char in expression.split(" "): if char.isdigit(): stack.push(int(char)) else: # I'm assuming that user input is valid. In "real world" project # it's necessary to check if is a valid operator. right = stack.pop() left = stack.pop() result = eval(f"{left}{char}{right}") stack.push(result) return stack.peek()
def evaluate(expression): operands = Stack() for token in expression: if isinstance(token, str): if token in OPERATORS: b = operands.pop() # second operand a = operands.pop() # first operand operands.push(calculate(a, b, token)) else: operands.push(token) return operands.pop()
class Queue: def __init__(self): self.s1 = Stack() self.s2 = Stack() def enqueue(self, val): while self.s1.size() > 0: self.s2.push(self.s1.pop()) self.s2.push(val) while self.s2.size() > 0: self.s1.push(self.s2.pop()) def dequeue(self): return self.s1.pop()
def test_pop_from_populated_stack(self): """Pop a value from a populated stack.""" s = Stack() s.push(self.single_value) popped = s.pop() self.assertEqual(popped, self.single_value) self.assertTrue(isinstance(popped, type(self.single_value)))
def test_pop(): stack = Stack() stack.push("a") stack.push("b") assert stack.pop() == "b" assert len(stack) == 1
def toStr(n, base): """ Convert given number to number in different base Instead of concatenating the result of the recursive call to toStr with the string from stringMap, Push the strings onto a stack instead of making the recursive call INPUT ------- n : Input number eg 1453 base : base to convert the number to eg. 16 or Hexadecimal RETURN ------- newStr = (1453,16) => 5AD """ tempStack = Stack() stringMap = '0123456789ABCDEF' newStr = '' while (n > 0): quotient = n // base remainder = n % base if remainder > 9: tempStack.push(stringMap[remainder]) else: tempStack.push(remainder) n = n // base while not tempStack.isEmpty(): newStr += str(tempStack.pop()) return newStr
def rev_string(test_str): string_stack = Stack() for ch in test_str: string_stack.push(ch) reverse_string = '' while not string_stack.isEmpty(): reverse_string = reverse_string + string_stack.pop() return reverse_string
def test_stack_push_pop(): el = 1 stack = Stack(5) stack.push(el) assert stack.size() == 1 assert stack.pop() == el assert stack.size() == 0
def test_pop(self): stack = Stack() stack.push('win') stack.push('test') item = stack.pop() self.assertEqual(item, 'test') self.assertEqual(stack.head.data, 'win')
def stack_reverse_string(input): stk = Stack() for elem in input: stk.push(elem) res = "" while stk.size() > 0: elem = stk.pop() res += elem return res
def test_pop(create_nodes, create_stack): n1, n2, n3 = create_nodes s = Stack() for ele in (n1, n2, n3): s.push(ele) assert s.head.next is n2 assert s.pop() == n3.value assert s.head is n2 assert s.head.next is n1 assert n3.next is None
class testPop(unittest.TestCase): def setUp(self): self.stack = Stack() def testEmptyList(self): self.assertRaises(IndexError, self.stack.pop) def testListOfOne(self): self.stack = Stack(1) self.assertEqual(self.stack.pop().val, 1) self.stack.push("Hello") self.assertEqual(self.stack.pop().val, "Hello") def testLongList(self): self.stack = Stack(10, 11, 12, 13, 14) self.assertEqual(self.stack.pop().val, 14) self.assertEqual(self.stack.pop().val, 13) def tearDown(self): self.stack = None
def testStack(self): stack = Stack() self.assertTrue(stack.isEmpty()) stack.push(5) self.assertFalse(stack.isEmpty()) stack.clear() self.assertTrue(stack.isEmpty()) stack.push(6) self.assertEqual(6, stack.top()) self.assertEqual(6, stack.pop()) self.assertTrue(stack.isEmpty()) stack.push(7) stack.push(6) stack.push(5) self.assertEqual(5, stack.pop()) self.assertEqual(6, stack.pop()) self.assertEqual(7, stack.top())
def test_pop_item(self): stack = Stack() stack.push("item") assert len(stack) > 0 assert len(stack) == 1 value = stack.pop() assert value == "item" assert len(stack) == 0 assert stack.peek() == None
def divide_by_2(dec_num): remstack = Stack() while dec_num > 0: rem = dec_num % 2 remstack.push(rem) dec_num = dec_num // 2 bin_string = "" while not remstack.isEmpty(): bin_string = bin_string + str(remstack.pop()) return bin_string
class TestStack(unittest.TestCase): def test_push_to_empty(self): self.my_stack = Stack() self.my_stack.push(5) self.assertEqual(5, self.my_stack.top.val) def test_push_to_non_empty(self): self.my_stack = Stack() self.my_stack.push(5) self.my_stack.push(4) self.assertEqual(4, self.my_stack.top.val) def test_pop_from_non_empty(self): self.my_stack = Stack() self.my_stack.push(5) self.assertEqual(5, self.my_stack.pop()) def test_pop_from_empty(self): self.my_stack = Stack() self.failureException("Uh oh!! You're trying to pop from an empty \ stack", self.my_stack.pop())
def route_exists(self, node1, node2): """ Returns whether a route exists between two nodes in the graph. """ stack = Stack() for node in self.get_nodes(): node.visited = False stack.push(node1) while not stack.is_empty(): node = stack.pop() if node: for child in node.get_children(): if not child.visited: if child is node2: return True else: stack.push(child) node.visited = True return False
def depth_first_traversal(self, start): if start not in self.nodes(): raise KeyError node = start stack = Stack() stack.push(node) traversed = [] while len(traversed) < len(self.nodes()): try: node = stack.pop() print node traversed.insert(0, node) children = self.neighbors(node) for child in children: if child not in traversed: stack.push(child) except LookupError: break traversed.reverse() return traversed
def test_push(items): s = Stack() for item in items: s.push(item) for item in reversed(items): assert s.pop() == item
def test_pop(items): s = Stack(items) for item in reversed(items): assert s.pop() == item with pytest.raises(IndexError): s.pop()
class BTree(object): def __init__(self, degree=2): self.root = Node() self.stack = Stack() if degree < 2: raise InvalidDegreeError self.degree = degree def __repr__(self): """For printing out the tree and its nodes It's here to save me typing during debugging""" result = '' for i in self._bft(): result += i return result def _bft(self): import queue keeper = queue.Queue() keeper.enqueue(self.root) while keeper.size() > 0: temp = keeper.dequeue() yield str(temp) if temp is not '\n' and temp.children[0]: keeper.enqueue('\n') for nod in temp.children: if nod is not None: keeper.enqueue(nod) def search(self, key): """Returns the value of the searched-for key""" nod, idx = self._recursive_search(self.root, key) return nod.elems[idx][1] def _recursive_search(self, node, key): """Searches the subtree for a specific key and returns where to find it if it is found If it is not found, raises a custom error""" # The index of the node in which the key is found idx = 0 while idx <= node.count - 1 and key > node.elems[idx][0]: # Look to the next key in the node idx += 1 if idx <= node.count - 1 and key == node.elems[idx][0]: # Found the key in the node return node, idx if not node.children[0]: raise MissingError else: # Look to the appropriate child return self._recursive_search(node.children[idx], key) def insert(self, key, val): """Inserts a key-value pair into the tree""" self._recursive_insert(self.root, key, val) def _split_child(self, parent, child): new = Node() for i in xrange(self.degree-1): new.add_to_node(*child.elems[i+self.degree]) child.del_from_node(i+self.degree) parent.add_to_node(*child.elems[self.degree-1]) child.del_from_node(self.degree-1) if child.children[0]: for i in xrange(self.degree): new.children[i], child.children[i+self.degree] = \ child.children[i+self.degree], None child.sort_children parent.children[2*self.degree-1] = new parent.sort_children() if parent.count == 2 * self.degree - 1: self._split_child(self.stack.pop().val, parent) def _recursive_insert(self, node, key, val): if not node.children[0]: node.add_to_node(key, val) if node.count == 2 * self.degree - 1: if node is self.root: new = Node() new.children[0], self.root = self.root, new self.stack.push(new) self._split_child(self.stack.pop().val, node) else: self.stack.push(node) idx = node.count - 1 while idx >= 0 and key < node.elems[idx][0]: idx -= 1 self._recursive_insert(node.children[idx+1], key, val) def delete(self, key): self._recursive_delete(self.root, key) def _recursive_delete(self, node, key): pass def _move_key(self, key, src, dest): pass def _merge_nodes(self, node1, node2): pass