def parens(string): """Return an integer representing whether all open parentheses are closed in order in the provided input. Args: string (unicode): The string to search through for parens. Returns: int: Value represents whether parens are matched: 1: There are open parens that are not closed. 0: There are an equal number of matched open and close parens. -1: There is a closed paren before a matching open paren. """ stack = Stack([-1, 0]) # ensure input is proper type before iterating for c in unicode(string): if c == '(': stack.push(1) elif c == ')': if stack.pop() == 0: # this is a 'broken' string break return stack.pop()
def buildParseTree(fpexp): fplist = fpexp.split() pStack = Stack() eTree = BinaryTree('') pStack.push(eTree) currentTree = eTree for i in fplist: if i == '(': currentTree.insertLeft('') pStack.push(currentTree) currentTree = currentTree.getLeftChild() elif i not in ['+', '-', '*', '/', ')']: currentTree.setRootVal(int(i)) parent = pStack.pop() currentTree = parent elif i in ['+', '-', '*', '/']: currentTree.setRootVal(i) currentTree.insertRight('') pStack.push(currentTree) currentTree = currentTree.getRightChild() elif i == ')': currentTree = pStack.pop() else: raise ValueError return eTree
class Queue_with_stacks: def __init__(self, iterable=[]): self.stack_back = Stack(iterable) self.stack_front = Stack() # import pdb; pdb.set_trace() def __topval__(self): if self.stack_back.top.val is None: print('Queue is empty') else: print('Next in queue is {}'.format(self.stack_back.top.val)) def enqueue(self, val): self.stack_back.push(val) print('{} added to end of Queue'.format(self.stack_back.top.val)) def dequeue(self): if self.stack_back.top is None: raise IndexError("queue is empty") x = None while self.stack_back.top._next: x = self.stack_back.pop() self.stack_front.push(x) # print('{} added to end of front Queue'.format(self.stack_front.top.val)) y = self.stack_back.pop() while self.stack_front.top: x = self.stack_front.pop() self.stack_back.push(x) # print('{} added to end of back Queue'.format(self.stack_back.top.val)) print('{} was removed from front of Queue'.format(y)) return y
class QueueUsingStack(object): def __init__(self): self._stack_one = Stack() self._stack_two = Stack() def __str__(self): return self._stack_one.__str__() def enqueue(self, element): ''' :param element: element to be enqueued in the queue ''' while not self._stack_one.is_empty(): self._stack_two.push(self._stack_one.pop()) self._stack_one.push(element) while not self._stack_two.is_empty(): self._stack_one.push(self._stack_two.pop()) return def dequeue(self): if self._stack_one.is_empty(): raise UnderflowException return self._stack_one.pop()
class TestStack(unittest.TestCase): def setUp(self): self.stack = Stack() def tearDown(self): return super().tearDown() def test_size(self): self.assertEqual(self.stack.size(), 0) def test_push(self): for i in range(10): self.stack.push(i) self.assertEqual(self.stack.size(), 10) def test_pop(self): for i in range(10): self.stack.push(i) self.assertEqual(self.stack.pop(), 9) def test_top(self): self.stack.push(1) self.assertEqual(self.stack.top(), 1) def test_pop_exception(self): self.assertIsNone(self.stack.pop()) def test_top_exception(self): self.assertIsNone(self.stack.top())
class TestStack(unittest.TestCase): def setUp(self) -> None: self.st = Stack() def test_is_empty(self): self.assertTrue(self.st.is_empty(), "The stack is not empty") self.assertRaises(IndexError, self.st.pop) def test_repr(self): self.assertEqual("Stack()", repr(self.st), "The repr method does not work properly") def test_push_one_item(self): self.st.push(2) self.assertFalse(self.st.is_empty()) self.assertEqual("Stack(2)", str(self.st)) def test_push_multiple_items(self): self.st.push(3) self.st.push(10) self.assertEqual("Stack(3, 10)", str(self.st)) popped_item = self.st.pop() self.assertEqual(10, popped_item) def test_is_full(self): for i in range(10): self.st.push(i) self.assertTrue(self.st.is_full()) self.assertRaises(OverflowError, self.st.push, 12) def test_pop_one_item(self): self.st.push(3) popped_item = self.st.pop() self.assertEqual(3, popped_item) def test_pop_multiple_items(self): self.st.push(3) self.st.push(10) popped_item = self.st.pop() self.assertEqual(10, popped_item) popped_item = self.st.pop() self.assertEqual(3, popped_item) def test_type(self): self.assertRaises(TypeError, self.st.push, "3") self.assertRaises(TypeError, self.st.push, 3.1) self.assertRaises(TypeError, self.st.push, True) def test_top_non_empty_stack(self): self.st.push(3) self.st.push(10) self.assertEqual(10, self.st.top()) def test_top_empty_stack(self): self.assertRaises(IndexError, self.st.top)
class AnimalShelter: def __init__(self, iterable=[]): self.stack_back = Stack(iterable) self.stack_front = Stack() # import pdb; pdb.set_trace() def __topval__(self): if self.stack_back.top.val is None: print('Queue is empty') else: print('Next in queue is {}'.format(self.stack_back.top.val)) def enqueue(self, val): self.stack_back.push(val) print('{} added to end of Queue'.format(self.stack_back.top.val)) def dequeue(self, pref): if self.stack_back.top is None: raise IndexError("queue is empty") x = None while self.stack_back.top._next: x = self.stack_back.pop() self.stack_front.push(x) # print('{} added to end of front Queue'.format(self.stack_front.top.val)) y = self.stack_back.pop() print(y) if y != 'cat' or 'dog': output = y while self.stack_front.top: x = self.stack_front.pop() self.stack_back.push(x) return output if str(y) == pref: output = y while self.stack_front.top: x = self.stack_front.pop() self.stack_back.push(x) return output else: self.stack_front.push(y) while self.stack_front.top: x = self.stack_front.pop() if x == pref: output = x else: self.stack_back.push(x) # print('{} added to end of back Queue'.format(self.stack_back.top.val)) print('oldest {} was removed from Queue'.format(output)) return output
def is_balanced_parentheses(string: str): stack = Stack() for char in string: if char == "(": stack.push("(") elif char == ")": if stack.isempty(): return False else: stack.pop() if stack.isempty(): return True else: return False
def is_balanced_symbols(string: str): stack = Stack() for char in string: if char in "([{": stack.push(char) elif char in "}])": if stack.isempty(): return False elif match(stack.peek(), char): stack.pop() else: return False if stack.isempty(): return True else: return False
def dfs_stack(root, fn): stack = Stack() stack.push(root) visited = defaultdict(bool) visited[root] = True fn(root) while not stack.is_empty(): node = stack.get_top() for child in node.get_children(): if not visited.get(child): fn(child) visited[child] = True stack.push(child) else: stack.pop()
def test_stack(self): e1 = Element(1) e2 = Element(2) e3 = Element(3) e4 = Element(4) stack = Stack(e1) stack.push(e2) stack.push(e3) assert stack.pop().value == 3 assert stack.pop().value == 2 assert stack.pop().value == 1 assert stack.pop() == None stack.push(e4) assert stack.pop().value == 4
def test_pop_from_non_empty_stack_(self): stack = Stack() stack.push(1) stack.push(5) stack.push(14) stack.push(31) self.assertEqual(stack.pop(), 31) self.assertEqual(stack.items.walk(), [1, 5, 14])
def dfs_stack(self): result = [] stack = Stack() stack.push(self) current_node = stack.peek() index = 0 while current_node and index < 8: for node in reversed(current_node.nodes): stack.push(node) current_node = stack.peek() if len(current_node.nodes) == 0: result.append(current_node.value) stack.pop() current_node = stack.peek() print(result) index += 1
def test_push_five_elements_to_stack_and_pop_all_elements(self): stack = Stack() langs = ['python', 'java', 'ruby', 'php', 'go'] for lang in langs: stack.push(lang) self.assertEqual(len(langs), stack.size()) for i in range(len(langs)): element = stack.pop() self.assertEqual(element, langs[len(langs) - i - 1]) self.assertTrue(stack.is_empty())
def fibonacci_iterative_stack(n): if n == 0: return 1 st = Stack(max_size=300) a, b = 1, 1 for _ in range(n): st.push(a) st.push(b) a, b = b, a + b return st.pop()
def reverse_string(input_string): s = Stack() for i in input_string: s.push(i) rev_string = '' while not s.is_empty(): rev_string = rev_string + (s.pop()) return rev_string
def stack_span(prices): st = Stack() nelements = len(prices) span = [0] * nelements for i in range(nelements): while not (st.is_empty()) and prices[st.top()] <= prices[i]: _ = st.pop() span[i] = i + 1 if st.is_empty() else i - st.top() st.push(i) return span
def test_push_five_elements_to_stack_and_pop_two_elements(self): stack = Stack() langs = ['python', 'java', 'ruby', 'php', 'go'] for lang in langs: stack.push(lang) self.assertEqual(len(langs), stack.size()) element1 = stack.pop() element2 = stack.pop() self.assertEqual('go', element1) self.assertEqual('php', element2) self.assertEqual(3, stack.size())
def pre_order_not_recursion(self): pre_order_list = [] node = self s = Stack() while node or not s.is_empty(): while node: pre_order_list.append(node) s.push(node) node = node.left if not s.is_empty(): node = (s.pop()).right return pre_order_list
class TestStack(unittest.TestCase): def setUp(self): self.data = ["d1", "d2"] self.s1 = Stack() self.s2 = Stack(StackNode(self.data[0])) self.s3 = Stack() for datum in self.data: self.s3.push(datum) def test_Stack__init__(self): self.assertEqual(self.s1.current, None) self.assertEqual(self.s1.len, 0) self.assertEqual(repr(self.s2.current), self.data[0]) self.assertEqual(self.s2.len, 1) def test_Stack__iter__(self): for n in self.s1: self.assertTrue(False) for s in [self.s2]: #, self.s3]: for n in s: self.assertTrue(repr(n) in self.data) def test_Stack_push(self): len1 = len(self.s1) self.s1.push("foo") self.assertTrue(len(self.s1) - len1 == 1) self.assertTrue(self.s1.peek() == "foo") len2 = len(self.s2) self.s2.push("bar") self.assertTrue(len(self.s2) - len2 == 1) self.assertTrue(self.s2.peek() == "bar") def test_Stack_pop(self): self.assertTrue(self.s3.pop() == self.data[1]) self.assertTrue(self.s3.pop() == self.data[0]) def test_Stack_peek(self): self.assertTrue(self.s3.peek() == self.data[1]) self.assertTrue(self.s3.peek() == self.data[1]) def test_Stack_isEmpty(self): self.assertTrue(self.s1.isEmpty()) self.assertFalse(self.s2.isEmpty()) def test_Stack__len__(self): self.assertEquals(len(self.s1), 0) self.assertEquals(len(self.s2), 1) self.assertEquals(len(self.s3), 2) def test_Stack__repr__(self): self.assertEquals(repr(self.s1), '') self.assertEquals(repr(self.s2), 'd1') self.assertEquals(repr(self.s3), 'd2 <- d1')
def in_order_not_recursion(self): in_order_list = [] node = self s = Stack() while node or not s.is_empty(): while node: s.push(node) node = node.left if not s.is_empty(): node = s.pop() in_order_list.append(node) node = node.right return in_order_list
def post_order_recursion(self): post_order_list = [] node = self pre_node = None current_node = None s = Stack() s.push(node) while not s.is_empty(): current_node = s.top() if (not current_node.left and not current_node.right) or \ (pre_node and ((current_node.left and pre_node.key == current_node.left.key) or (current_node.right and pre_node.key == current_node.right.key))): post_order_list.append(current_node) s.pop() pre_node = current_node else: if current_node.right: s.push(current_node.right) if current_node.left: s.push(current_node.left) return post_order_list
def dfs_in_order_stack(self): result = [] stack = Stack() stack.push(self) while stack.peek(): current_node = stack.pop() result.append(current_node.value) for node in current_node.nodes: stack.push(node) return result
def dft_print(self, node): # in order, just with an iterative solution s = Stack() while node is not None: if node.left: s.push(node.left) print(node.value) if node.right: s.push(node.right) if len(s) > 0: node = s.pop() else: break return
def dft_print(self, node): s = Stack() s.push(node) x_arr = [] while s.size > 0: current_node = s.pop() print(current_node.value) x_arr.append(current_node.value) if current_node.left: s.push(current_node.left) if current_node.right: s.push(current_node.right)
class BufferedQueue: def __init__(self, limit): self.limit = limit self.enqueued = Stack() self.dequeued = Stack() def __str__(self): return self.enqueued.__str__() + self.dequeued.__str__( ) + f' buffer limit {self.limit}' def enqueue(self, item): if self.size() < self.limit: self.enqueued.push(item) return True else: return False def dequeue(self): if self.dequeued.size() > 0: return self.dequeued.pop() while self.enqueued.size() > 1: self.dequeued.push(self.enqueued.pop()) return self.enqueued.pop() def next(self): if self.dequeued.size() > 0: return self.dequeued.last() else: return self.enqueued.first() def last(self): if self.enqueued.size() > 0: return self.enqueued.last() else: return self.dequeued.first() def size(self): return self.enqueued.size() + self.dequeued.size()
def test_stack(self): elements = [5, 1, 6, 9, 72, 42, 51] expected_result = elements.copy() expected_result.reverse() stack = Stack() for element in elements: stack.push(element) actual_result = [] while stack.peek(): actual_result.append(stack.pop()) self.assertEqual(expected_result, actual_result)
def dft_print(self, node): stack = Stack() stack.push(node) while stack.__len__() > 0: top_item = stack.pop() print(top_item.value) if top_item.right is not None: stack.push(top_item.right) if top_item.left is not None: stack.push(top_item.left)
def dft_print(self, node): stack = Stack() # .push will add new elements stack.push(node) while len(stack) > 0: # pop is used to return nth element of list node = stack.pop() if node.left is not None: stack.push(node.left) if node.right is not None: stack.push(node.right) print(node.value)
def size(self): if self.root is None: return 0 stack = Stack() stack.push(self.root) size = 1 while not stack.is_empty(): node = stack.pop() if node.left: size += 1 stack.push(node.left) if node.right: size += 1 stack.push(node.right) return size
def infix2postfix(infix): s = Stack() l = [] linfix = infix.split() priority = {"*": 3, "/": 3, "+": 2, "-": 2, "(": 1} for i in linfix: if i == "(": s.push(i) elif i == ")": t = s.pop() while not s.is_empty() and t != "(": l.append(t) t = s.pop() elif i in "+-*/": while not s.is_empty() and priority[s.peek()] >= priority[i]: l.append(s.pop()) s.push(i) else: l.append(i) while not s.is_empty(): l.append(s.pop()) return " ".join(l)
def ackermann_iterative(m, n): st = Stack() st.push(m) while len(st): m = st.pop() if m == 0: n += 1 elif n == 0: n = 1 st.push(m - 1) else: st.push(m - 1) st.push(m) n -= 1 return n
class ParenthesisMatching(object): def __init__(self, parenthesis): self.parenthesis = parenthesis self.stack = Stack() def is_match(self): maps = {")": "(", "]": "[", "}": "{"} for p in self.parenthesis: if p in "([{": self.stack.push(p) elif p in ")]}": if self.stack.is_empty(): return False else: top = self.stack.pop() if maps[p] != top: return False return True
class BitConversion(object): def __init__(self, dec): self.dec = dec self.stack = Stack() self.base = "0123456789abcdef" def conversion(self, bit): if bit not in (2, 8, 16): raise ValueError("bit must in (2, 8, 16)") while self.dec > 0: remainder = self.dec % bit self.stack.push(self.base[remainder]) self.dec = self.dec // bit result = [] while not self.stack.is_empty(): result.append(self.stack.pop()) return "".join(result)
def pre_order_traverse(root): """ please refer to http://learn.hackerearth.com/tutorial/trees/19/iterative-tree-traversals/ """ stack = Stack() p = root while True: while p is not None: # print node and store the node in the stack print p, stack.push(p) p = p.lchild # visit the right child if not stack.is_empty(): p = stack.pop() p = p.rchild if stack.is_empty() and p is None: break print
def in_order_traverse(root): """ please refer to http://learn.hackerearth.com/tutorial/trees/19/iterative-tree-traversals/ """ stack = Stack() p = root while True: while p is not None: # store a node in the stack and visit its left child stack.push(p) p = p.lchild # if there are nodes in the stack to which we can move up, then pop it if not stack.is_empty(): p = stack.pop() print p, # visit the right child p = p.rchild if stack.is_empty() and p is None: break print
from stack.stack import Stack from stack.stack import foo stk = Stack() stk.push(1) stk.push(2) stk.pop() stk.push(3) print stk.peek() print stk.size() print foo()
class StackTests(unittest.TestCase): def setUp(self): self.stack = Stack() def tearDown(self): self.stack = None def test_push(self): self.stack.push(10) self.assertEqual(self.stack.peek(), 10) self.stack.push(100) self.assertEqual(self.stack.peek(), 100) def test_pop(self): self.stack.push(1) self.stack.push(2) self.stack.push(3) self.stack.push(4) self.assertEquals(self.stack.pop(), 4) self.assertEquals(self.stack.pop(), 3) self.assertEquals(self.stack.pop(), 2) self.assertEquals(self.stack.pop(), 1) with self.assertRaises(IndexError): self.stack.pop() def test_peek(self): self.stack.push(1) self.stack.push(2) self.stack.push(3) self.stack.push(4) self.assertEquals(self.stack.peek(), 4) self.stack.pop() self.assertEquals(self.stack.peek(), 3) self.stack.pop() self.assertEquals(self.stack.peek(), 2) self.stack.pop() self.assertEquals(self.stack.peek(), 1) self.stack.pop() with self.assertRaises(IndexError): self.stack.peek() def test_reverse(self): self.stack.push(1) self.stack.push(2) self.stack.push(3) self.stack.push(4) self.stack.push(5) self.stack.reverse() self.assertEqual(self.stack.pop(), 1) self.assertEqual(self.stack.pop(), 2) self.assertEqual(self.stack.pop(), 3) self.assertEqual(self.stack.pop(), 4) self.assertEqual(self.stack.pop(), 5)