def __init__(self, serial_num, host=None, port=None): log("%s.%s serial_num=%s host=%s port=%s", self.__class__, self.__init__.__name__, serial_num, host, port) self.serial_num = serial_num if host: self.host = host else: self.host = _adb_get_ip(self.serial_num) if port: self.port = port else: self.port = self.PORT_DEFAULT self._btp_socket = None self._btp_worker = None # self.log_filename = "iut-mynewt-{}.log".format(id) # self.log_file = open(self.log_filename, "w") self._stack = Stack() self._stack.set_pairing_consent_cb( lambda addr: _adb_tap_ok(self.serial_num)) self._stack.set_passkey_confirm_cb( lambda addr, match: _adb_tap_ok(self.serial_num)) self._event_handler = BTPEventHandler(self)
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
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_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 main(): discs_count = 4 tower1: Stack[int] = Stack() tower2: Stack[int] = Stack() tower3: Stack[int] = Stack() for i in range(discs_count, 0, -1): tower1.push(i) print(tower1, tower2, tower3) solve(tower1, tower3, tower2, discs_count) print(tower1, tower2, tower3)
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()
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 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 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 small_stack(): s = Stack() s.push(1) s.push(2) s.push(3) s.push(4) s.push(5) return s
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 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 __init__(self): self.procedure_directory = {} # [name] = {type, var_table} self.curr_dimension_counter = 0 # last defined array dimension counter self.curr_scope = "" # The current scope inside the program self.curr_slice = None self.curr_r = 1 self.curr_type = "" # The current type used (module or var) self.curr_module_param_counter = 0 self.curr_module_var_counter = 0 self.queue_params = [] self.queue_params_addresses = [] self.stack_calls = Stack() self.stack_calls.push(999) self.stack_param_pointers = Stack() self.stack_param_pointers.push(0) self.is_value_slice_enabled = True
def __init__(self, host, port): log("%s.%s host=%s port=%s", self.__class__, self.__init__.__name__, host, port) self.host = host self.port = port self._btp_socket = None self._btp_worker = None # self.log_filename = "iut-mynewt-{}.log".format(id) # self.log_file = open(self.log_filename, "w") self._stack = Stack() self._stack.set_pairing_consent_cb(_pairing_consent) self._stack.set_passkey_confirm_cb(_passkey_confirm) self._event_handler = BTPEventHandler(self)
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 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)
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)
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
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])
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 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_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_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 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 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_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 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 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 __init__(self, board: Board): log("%s.%s board=%r", self.__class__, self.__init__.__name__, board) self.board = board self.id = self.board.id self.btp_address = BTP_ADDRESS + '-' + str(self.id) self._socat_process = None self._btp_socket = None self._btp_worker = None self.log_filename = "iut-mynewt-{}.log".format(self.id) self.log_file = open(self.log_filename, "w") self._stack = Stack() self._event_handler = BTPEventHandler(self)
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 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 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
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()
def setUp(self): self.stack = Stack()
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)