Exemplo n.º 1
0
    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)
Exemplo n.º 2
0
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
Exemplo n.º 3
0
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
Exemplo n.º 5
0
 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])
Exemplo n.º 6
0
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
Exemplo n.º 12
0
 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
Exemplo n.º 13
0
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()
Exemplo n.º 14
0
 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
Exemplo n.º 15
0
    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)
Exemplo n.º 16
0
    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
Exemplo n.º 17
0
    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)
Exemplo n.º 18
0
    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)
Exemplo n.º 19
0
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
Exemplo n.º 20
0
 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])
Exemplo n.º 21
0
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)
Exemplo n.º 22
0
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
Exemplo n.º 23
0
    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
Exemplo n.º 24
0
 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())
Exemplo n.º 25
0
 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)
Exemplo n.º 26
0
 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)
Exemplo n.º 27
0
 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())
Exemplo n.º 28
0
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
Exemplo n.º 30
0
    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
Exemplo n.º 32
0
 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
Exemplo n.º 33
0
 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
Exemplo n.º 34
0
    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
Exemplo n.º 35
0
    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
Exemplo n.º 36
0
    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
Exemplo n.º 37
0
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()
Exemplo n.º 38
0
 def setUp(self):
     self.stack = Stack()
Exemplo n.º 39
0
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)