def test_popping_from_stack_returns_last_item():
    stack = Stack()
    stack.push(1)
    stack.push(2)
    stack.push(3)

    assert_equal(stack.pop(), 3)
def test_pushing_to_stack_adds_item_to_stack():
    stack = Stack()

    assert_equal(stack.empty(), True)
    stack.push(1)
    assert_equal(stack.empty(), False)
    assert_equal(stack.peek(), 1)
def test_popping_from_stack_removes_item():
    stack = Stack()
    stack.push(1)

    assert_equal(stack.empty(), False)
    assert_equal(stack.pop(), 1)
    assert_equal(stack.empty(), True)
def test_peeking_at_stack_does_not_remove_item():
    stack = Stack()
    stack.push(1)

    assert_equal(stack.empty(), False)
    assert_equal(stack.peek(), 1)
    assert_equal(stack.empty(), False)
Exemple #5
0
def main():
    print "\ncheck stack"
    stack = Stack(1, 2, 34, 5)
    for x in range(0, 5):
        stack.push(x)
    print stack
    for x in range(0, 15):
        print "".join(["size=", str(len(stack)), " cur_node=", str(stack.pop())])

    print "\ncheck queue"
    queue = Queue(1, 2, 34, 5)
    for x in range(0, 5):
        queue.enter(x)
    print stack
    for x in range(0, 15):
        print "".join(["size=", str(len(queue)), " cur_node=", str(queue.exit())])

    print "\ncheck BSTree"
    tree = BSTree(1, 2, 34, 5)
    print tree
    print tree.find(10)
    print tree.find(5)
    print tree.max()
    print tree.min()
    print tree.successor(34)
    print tree.successor(5)
    print tree.predecessor(1)
    print tree.predecessor(2)
Exemple #6
0
    def midorder(self, f):
        """
        B树中序遍历
        :param f:
        :return:
        """
        result = []
        stack = Stack()
        cur_node = self.__root
        if cur_node.is_leaf:
            return map(f, cur_node.keys)

        while True:
            if cur_node.is_leaf:
                # 到叶节点了,开始把叶节点的所有关键字都遍历掉
                result.extend(map(f, cur_node.keys))
                # 开始从栈中取元素,遍历下一个节点叶节点
                if stack.empty():
                    return result
                cur_node, i = stack.pop()
                result.append(f(cur_node.keys[i]))
                if i < len(cur_node) - 1:
                    stack.push((cur_node, i + 1))
                cur_node = cur_node.childs[i + 1]
            else:
                stack.push((cur_node, 0))
                cur_node = cur_node.childs[0]
        return result
def test_peeking_at_stack_returns_last_item():
    stack = Stack()
    stack.push(1)
    stack.push(2)
    stack.push(3)

    assert_equal(stack.peek(), 3)
Exemple #8
0
def init_stacks(size):
  left   = Stack()
  middle = Stack()
  right  = Stack()

  for item in range(1, size + 1):
    left.push(item)

  return (left, middle, right)
Exemple #9
0
 def test_stack_is_empty(self):
     stk = Stack()
     random_values = get_random_values()
     self.assertEqual(stk.is_empty(), True)
     for v in random_values:
         stk.push(v)
         self.assertEqual(stk.is_empty(), False)
     for v in random_values[::-1]:
         self.assertEqual(stk.is_empty(), False)
         stk.pop()
     self.assertEqual(stk.is_empty(), True)
Exemple #10
0
def base_converter(dec_number, base):
    digits = "0123456789ABCDEF"
    tmp = Stack()
    string = ""
    while dec_number != 0:
        tmp.push(dec_number % base)
        dec_number //= base
    while not tmp.isEmpty():
        string += digits[tmp.pop()]

    return string
def dec_to_bin(dec):
    # Finish the function
    s=Stack()
    while dec!=0:
        s.push(dec%2)
        dec=dec//2
        
    binary=[]
    while not s.isEmpty():
        binary.append(s.pop())
        
    return binary
def dec_to_bin(dec):
    s = Stack()
    while(dec>0):
        s.push(dec%2)
        dec // 2
    binary = 0

    for i in range(s.size()):
        num = s.pop()
        binary += num*(10**s.size())
    
    return binary
Exemple #13
0
 def test_stack_pop(self):
     stk = Stack()
     random_values = get_random_values()
     for v in random_values:
         stk.push(v)
     for v in random_values[::-1]:
         stk.pop()
     self.assertEqual(stk.is_empty(), True)
     with self.assertRaises(IndexError):
         stk.pop()
     with self.assertRaises(IndexError):
         stk.peek()
def base_converter(dec_number, base):
    digits = "0123456789ABCDEF"
    s=Stack()
    while dec_number!=0:
        s.push(digits[dec_number%base])
        dec_number=dec_number//base
        
    string=''
    while not s.isEmpty():
        string=string+s.pop()
    
    return string
Exemple #15
0
def dec_to_bin(dec):
    binary = ''
    s = Stack()
    while dec != 0:
        tmp = dec % 2
        dec = dec // 2
        s.push(tmp)

    while s.size() != 0:
        a = s.pop()
        binary += str(a)
    return binary
Exemple #16
0
def sort_stack(stack):
    sorted_stack = stack
    stack = Stack()

    while not sorted_stack.is_empty():
        stack.push(sorted_stack.pop())

    while not stack.is_empty():
        tmp = stack.pop()
        while not sorted_stack.is_empty() and sorted_stack.peek() < tmp:
            stack.push(sorted_stack.pop())
        sorted_stack.push(tmp)
Exemple #17
0
    def remove_even(self):
        tstack = Stack()

        # empty the stack and store even numbers in
        # another, temporary stack (in reverse order)
        while not self.empty:
            popped = self.pop()
            if popped % 2 == 1:
                tstack.push(popped)

        # move the data from temporary stack back to original
        while not tstack.empty:
            self.push(tstack.pop())
 def preorder(self, f):
     result = []
     stack = Stack(self.__root)
     while True:
         cur_node = stack.pop()
         # 栈中没有元素的时候就表示所有的元素都已经遍历完了
         if cur_node is None:
             break
         result.append(f(cur_node.value))
         if cur_node.left is not None:
             stack.push(cur_node.left)
         if cur_node.right is not None:
             stack.push(cur_node.right)
     return result
Exemple #19
0
    def test_stack_reversed_with_override(self):
        self.assertEqual(list(reversed([123, 456])), [456, 123])

        stk = Stack()
        random_values = get_random_values()
        for v in random_values:
            stk.push(v)
        reversed_stk = reversed(stk)
        for v in random_values:
            self.assertEqual(reversed_stk.peek(), v)
            reversed_stk.pop()
        self.assertEqual(stk.size(), len(random_values))

        self.assertEqual(list(reversed([123, 456])), [456, 123])
def dec_to_bin(dec):
    s = Stack()
    n = dec
    if n == 0:
        s.push(n % 2)
        n = n // 2

    while n > 0:
        s.push(n % 2)
        n = n // 2
    number = s.size()
    binary = ''
    for i in range(number):
        binary = binary + str(s.pop())
    return binary
 def midorder(self, f):
     result = []
     stack = Stack(self.__root)
     cur_node = self.__root.left
     # 第一个阶段首先把所有树左边的节点放进栈里,这个时候并不遍历
     # 第二个阶段的时候由于左节点遍历了之后,再遍历右节点
     while not stack.empty() or cur_node is not None:
         # 第二个判断条件比较重要,因为如果根节点没有左子树,这个时候栈就是空的,会直接退出循环
         if cur_node is not None:
             stack.push(cur_node)
             cur_node = cur_node.left
         else:
             cur_node = stack.pop()
             result.append(f(cur_node.value))
             cur_node = cur_node.right
     return result
def dec_to_bin2(dec):
    s = Stack()
    i = 0
    for j in range(10000):
        if(dec // (2**j) == 0):
            i = j
            break
    binary = 0
    for k in range(i):
        k = i - k
        if(dec % (2 ** k) // (2 ** (k-1)) == 1):
            s.push(1)
        else:
            s.push(0)
    for l in range(s.size()):
        binary += s.pop() * (10 ** l)
    return binary
def base_converter(dec_number, base):
    digits = "0123456789ABCDEF"
    s = Stack()
    n = dec_number
    while n > 0:
        number = n % base
        if number > 9:
            s.push(digits[number])
        else:
            s.push(n % base)
        n = n // base
    number = s.size()
    string = ''
    for i in range(number):
        string = string + str(s.pop())

    return string
Exemple #24
0
def base_converter(dec, base):
    binary = ''
    s = Stack()

    while dec != 0:
        if base > 16 or base < 2:  #若base輸入值不符合範圍,輸出error
            return "error"

        tmp = dec % base
        dec = dec // base

        if tmp >= 10:
            d = tmp % 10
            tmp = chr(65 + d)
        s.push(tmp)

    while s.size() != 0:
        a = s.pop()
        binary += str(a)
    return binary
Exemple #25
0
 def midorder(self, f):
     """
     中序遍历
     :param f:访问一个节点的时候要对节点进行处理的函数
     :return:
     """
     result = []
     stack = Stack(self.__root)
     cur_node = self.__root.left
     # 第一个阶段首先把所有树左边的节点放进栈里,这个时候并不遍历
     # 第二个阶段的时候由于左节点遍历了之后,再遍历右节点
     while not stack.empty() or cur_node is not self.Nil:
         # 第二个判断条件比较重要,因为如果根节点没有左子树,这个时候栈就是空的,会直接退出循环
         if cur_node is not self.Nil:
             stack.push(cur_node)
             cur_node = cur_node.left
         else:
             cur_node = stack.pop()
             result.append(f(cur_node))
             cur_node = cur_node.right
     return result
Exemple #26
0
 def midorder(self, f):
     """
     中序遍历
     :param f:访问一个节点的时候要对节点进行处理的函数
     :return:
     """
     result = []
     stack = Stack(self.__root)
     cur_node = self.__root.left
     # 第一个阶段首先把所有树左边的节点放进栈里,这个时候并不遍历
     # 第二个阶段的时候由于左节点遍历了之后,再遍历右节点
     while not stack.empty() or cur_node is not self.Nil:
         # 第二个判断条件比较重要,因为如果根节点没有左子树,这个时候栈就是空的,会直接退出循环
         if cur_node is not self.Nil:
             stack.push(cur_node)
             cur_node = cur_node.left
         else:
             cur_node = stack.pop()
             result.append(f(cur_node))
             cur_node = cur_node.right
     return result
Exemple #27
0
class MinStack:
  def __init__(self):
    self.mins  = Stack()
    self.items = Stack()

  def push(self, item):
    min = self.mins.peek()
    if min == None or item < min:
      self.mins.push(item)

    return self.items.push(item)

  def pop(self):
    item = self.items.pop()
    if item == self.mins.peek():
      self.mins.pop()

    return item

  def min(self):
    return self.mins.peek()
Exemple #28
0
class SetOfStacks:
  def __init__(self, capacity):
    self.capacity = capacity
    self.stacks = [Stack()]
    self.active_stack_index = 0
    self.active_stack = self.stacks[0]

  def update_active_stack_next(self):
    if self.active_stack.size < self.capacity:
      return

    self.active_stack = Stack()
    self.stacks.append(self.active_stack)
    self.active_stack_index += 1

  def update_active_stack_prev(self):
    if self.active_stack.size > 0:
      return

    if self.active_stack_index == 0:
      return

    self.active_stack_index -= 1
    self.active_stack = self.stacks[self.active_stack_index]
    self.update_active_stack_prev()

  def push(self, data):
    self.update_active_stack_next()
    self.active_stack.push(data)
    return data

  def pop(self):
    self.update_active_stack_prev()
    return self.active_stack.pop()

  def pop_at(self, index):
    stack = self.stacks[index]
    if stack:
      return stack.pop()
    def dfs(self, gray_func, black_func):
        """
        图的深度遍历
        :param gray_func:
        :param black_func:
        :return:
        """
        gray_list = []
        black_list = []

        # 初始化
        for key in self.__dict.iterkeys():
            key.start_time = None
            key.end_time = None
            key.set_white()

        # 开始遍历
        counter = 0
        for key in self.__dict.iterkeys():
            if key.is_white():
                dfs_stack = Stack()
                key.set_gray()
                key.start_time = counter
                counter += 1
                dfs_stack.push(key)
                while not dfs_stack.empty():
                    cur_node = dfs_stack.pop()
                    gray_list.append(gray_func(key))
                    for end_node in self.__dict[cur_node]:
                        if end_node.is_white():
                            end_node.set_gray()
                            end_node.start_time = counter
                            counter += 1
                            dfs_stack.push(end_node)
                    cur_node.set_black()
                    black_list.append(black_func(cur_node))
                    cur_node.end_time = counter
                    counter += 1
        return gray_list, black_list
Exemple #30
0
class TestStack(unittest.TestCase):
    def setUp(self):
        # Create stacks for the tests to use
        self.new = Stack()
        self.empty = Stack()
        self.empty.push('hi')
        self.empty.pop()
        # Don't add in ascending or descending order
        self.non_empty = Stack()
        self.non_empty.push(5)
        self.non_empty.push(2)
        self.non_empty.push(7)
        self.non_empty.push(2)

    def test_length(self):
        self.assertEqual(len(self.new), 0)
        self.assertEqual(len(self.empty), 0)
        self.assertEqual(len(self.non_empty), 4)

    def test_is_empty(self):
        self.assertTrue(self.new.is_empty())
        self.assertTrue(self.empty.is_empty())
        self.assertFalse(self.non_empty.is_empty())

    def test_lifo_order(self):
        self.assertEqual(self.non_empty.pop(), 2)
        self.assertEqual(self.non_empty.pop(), 7)
        self.assertEqual(self.non_empty.pop(), 2)
        self.assertEqual(self.non_empty.pop(), 5)

    def test_access_to_empty(self):
        with self.assertRaises(AssertionError):
            self.new.top()
        with self.assertRaises(AssertionError):
            self.empty.top()
        with self.assertRaises(AssertionError):
            self.new.pop()
        with self.assertRaises(AssertionError):
            self.empty.pop()

    def test_membership(self):
        self.assertFalse(2 in self.new)
        self.assertFalse(2 in self.empty)
        self.assertTrue(2 in self.non_empty)
        self.assertTrue(5 in self.non_empty)
        self.assertTrue(7 in self.non_empty)
Exemple #31
0
    def traversal_graph_dfs(self, ip_address):
        if not self.graph_db:
            msg = "Traversal graph by dfs requires initialization of a graph database!"
            throw_error(msg, TraversalGraphException)

        self.graph = {}
        self.graph_db.start_db()

        try:
            next_vertex_id = self.get_next_vertex_id()

            default_ports = set_api_default_port()
            root_id = self.get_vertex_id_with_ip(ip_address)

            if not root_id:
                if root_id != 0:
                    root_id = next_vertex_id
                    next_vertex_id += 1
                    root_basic_info = [ip_address, root_id, default_ports[0]]
                    self.add_vertex_to_table_nodes_id(root_basic_info)

            root_name = ''
            root_nonce = ''
            root = Node(root_id, ip_address, default_ports, root_name,
                        root_nonce)
            self.root_update = False

            self.graph.update({ip_address: root})
            node_stack = Stack()
            node_stack.push(ip_address)

            start_time = timeit.default_timer()

            while not node_stack.is_empty():
                _vertex_ip = node_stack.pop()
                _vertex = self.graph[_vertex_ip]

                if not _vertex.visited:
                    _vertex.visited = True
                    if _vertex.status:
                        node_start_time = timeit.default_timer()
                        url = _vertex.link
                        peers = get_peer_nodes(url)
                        if peers:
                            if peers[0][
                                    'applicationName'] != self.application_name:
                                _vertex.status = False
                                _vertex.link = 'wrong application'
                                continue
                        peers_id = []
                        for item in peers:
                            [_peer_ip, port, peer_name,
                             peer_nonce] = parse_ip_port_name_nonce(item)
                            _peer_id = self.get_vertex_id_with_ip(_peer_ip)
                            if not _peer_id:
                                if _peer_id != 0:
                                    _peer_id = next_vertex_id
                                    new_node = Node(_peer_id, _peer_ip,
                                                    default_ports + [port],
                                                    peer_name, peer_nonce)
                                    new_node_basic_info = [
                                        _peer_ip, _peer_id, new_node.port
                                    ]

                                    self.add_vertex_to_table_nodes_id(
                                        new_node_basic_info)
                                    next_vertex_id += 1
                                    if _peer_ip not in self.graph:
                                        self.graph.update({_peer_ip: new_node})
                                else:
                                    if _peer_ip not in self.graph:
                                        new_node = Node(
                                            _peer_id, _peer_ip,
                                            default_ports + [port], peer_name,
                                            peer_nonce)
                                        self.graph.update({_peer_ip: new_node})
                            else:
                                if _peer_ip not in self.graph:
                                    new_node = Node(_peer_id, _peer_ip,
                                                    default_ports + [port],
                                                    peer_name, peer_nonce)
                                    self.graph.update({_peer_ip: new_node})

                            _peer = self.graph[_peer_ip]

                            if _peer_ip != _vertex_ip:
                                peers_id.append(_peer_id)

                            self.update_root_name_nonce(
                                root, _peer_id, peer_name, peer_nonce)

                            if not _peer.visited:
                                node_stack.push(_peer_ip)

                        _vertex.peers = list(dict.fromkeys(peers_id))
                        node_stop_time = timeit.default_timer()
                        _vertex.time_get_basic_info = node_stop_time - node_start_time

            stop_time = timeit.default_timer()
            self.time_traversal_graph = stop_time - start_time

        except TraversalGraphException:
            msg = "Traversal graph by dfs has error!"
            throw_error(msg, TraversalGraphException)

        # finally:
        #     self.graph_db.close_db()

        print("time of traversing the current graph: ",
              self.time_traversal_graph)
        print("total number of vertex in the current graph: ", len(self.graph))
Exemple #32
0
def reverse(stack):
    rstack = Stack()
    while not stack.empty:
        rstack.push(stack.pop())
    return rstack
Exemple #33
0
def finding_cheese(map, mouse):
    s = Stack()
    sx = Stack()
    sy = Stack()
    for i in range(10000):
        if(s.isEmpty() == False):
            j = s.pop()
        k = 1
        if((map[mouse[0]][mouse[1]+1] == 0 or map[mouse[0]][mouse[1]+1] == 5) and k == 1):
            if(map[mouse[0]][mouse[1]+1] == 5):
                sx.push(mouse[0])
                sy.push(mouse[1])
                cheese = [[mouse[0], mouse[1]+1]]
                while(sx.isEmpty() == False):
                    cheese += [[sx.pop(), sy.pop()]]
                return cheese
            sx.push(mouse[0])
            sy.push(mouse[1])
            map[mouse[0]][mouse[1]+1] = 2
            mouse[1] += 1
            s.push(0)
            k = 1
        elif((map[mouse[0]+1][mouse[1]] == 0 or map[mouse[0]+1][mouse[1]] == 5) and (k == 1 or j == 0)):
            if(map[mouse[0]+1][mouse[1]] == 5):
                sx.push(mouse[0])
                sy.push(mouse[1])
                cheese = [[mouse[0]+1, mouse[1]]]
                while(sx.isEmpty() == False):
                    cheese += [[sx.pop(), sy.pop()]]
                return cheese
            sx.push(mouse[0])
            sy.push(mouse[1])
            map[mouse[0]+1][mouse[1]] = 2
            mouse[0] += 1
            s.push(1)
            k = 1
        elif((map[mouse[0]][mouse[1]-1] == 0 or map[mouse[0]][mouse[1]-1] == 5) and (k == 1 or j == 1)):
            if(map[mouse[0]][mouse[1]-1] == 5):
                sx.push(mouse[0])
                sy.push(mouse[1])
                cheese = [[mouse[0], mouse[1]-1]]
                while(sx.isEmpty() == False):
                    cheese += [[sx.pop(), sy.pop()]]
                return cheese
            sx.push(mouse[0])
            sy.push(mouse[1])
            map[mouse[0]][mouse[1]-1] = 2
            mouse[1] -= 1
            s.push(2)
            k = 1
        elif((map[mouse[0]-1][mouse[1]] == 0 or map[mouse[0]-1][mouse[1]] == 5) and (k == 1 or j == 2)):
            if(map[mouse[0]-1][mouse[1]] == 5):
                sx.push(mouse[0])
                sy.push(mouse[1])
                cheese = [[mouse[0]-1, mouse[1]]]
                while(sx.isEmpty() == False):
                    cheese += [[sx.pop(), sy.pop()]]
                return cheese
            sx.push(mouse[0])
            sy.push(mouse[1])
            map[mouse[0]-1][mouse[1]] = 2
            mouse[0] -= 1
            s.push(3)
            k = 1
        else:
            k = 0
            mouse[0] = sx.pop()
            mouse[1] = sy.pop()
def test_empty_returning_false_when_not_empty():
    stack = Stack()
    stack.push(1)

    assert_equal(stack.empty(), False)
Exemple #35
0
 def test_pop(self):
     s = Stack()
     s.push(Slice(1, 2, 3))
     assert s.pop().__str__() == '1,2,3 R0'
     assert s.__len__() == 0
Exemple #36
0
 def test_validate(self):
     s = Stack()
     s.push(Slice(1, 2, 3))
     s.push(Slice(3, 4, 5))
     assert s.isValid()
Exemple #37
0
 def test_iter(self):
     s = Stack()
     s.push(Slice(1, 2, 3))