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 large_stack(): s = Stack() for num in range(1000): s.push(num) return s
def test_push_to_non_empty_stack(self): stack = Stack() stack.push(2) self.assertIsNotNone(stack.items.head) stack.push(4) self.assertNotEqual(stack.items.head.value, 4) self.assertEqual(stack.items.tail.value, 4)
def test_push_five_elements_and_iterate_stack(self): stack = Stack() langs = ['python', 'java', 'ruby', 'php', 'go'] for lang in langs: stack.push(lang) self.assertEqual(len(langs), stack.size()) for index, element in enumerate(stack): self.assertEqual(element, langs[len(langs) - index - 1])
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 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 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 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 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 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
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 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 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 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 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 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 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 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
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 reverse_levelorder_print(self, start, traversal): if start is None: return queue = Queue() stack = Stack() queue.enqueue(start) while len(queue) > 0: node = queue.dequeue() stack.push(node) if node.right: queue.enqueue(node.right) if node.left: queue.enqueue(node.left) while not stack.is_empty(): node = stack.pop() traversal += str(node.value) + '-' return traversal
def is_paren_balanced(paren_string): s = Stack() index = 0 while index < len(paren_string): paren = paren_string[index] if paren in '{[(': s.push(paren) else: if s.is_empty(): return False else: last_paren = s.pop() if not is_match(last_paren, paren): return False index += 1 return True
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 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 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 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
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
class PostfixCalculator(object): def __init__(self, tokens_string=""): self._tokens_string = tokens_string self._stack = Stack() self._result = 0 @property def tokens(self): return self._tokens_string def _tokenize(self): return self._tokens_string.split() def _do_operation(self, operator): # """ This method mimics a switch statement """ rhs = self._stack.pop() # right hand side operand lhs = self._stack.pop() # left hand side operand # switch return { "+": int(lhs) + int(rhs), "-": int(lhs) - int(rhs), "*": int(lhs) * int(rhs), "/": int(lhs) / int(rhs), }.get(operator, "unknown operator {}".format(operator)) def calculate(self): """ Execute postfix algorithm here """ tokens = self._tokenize() for token in tokens: try: self._stack.push(int(token)) except ValueError: self._stack.push(self._do_operation(token)) # Peek at the top of the stack to get the result self._result = self._stack.peek() @property def result(self): return self._result
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
def small_stack(): s = Stack() s.push(1) s.push(2) s.push(3) s.push(4) s.push(5) return s
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_peep_from_non_empty_stack_(self): stack = Stack() stack.push(5) self.assertEqual(stack.peek(), 5) stack.push(10) self.assertEqual(stack.peek(), 10) stack.push(19) self.assertEqual(stack.peek(), 19) self.assertEqual(stack.items.walk(), [5, 10, 19])
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
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)