예제 #1
0
class MaxStack:
    def __init__(self, data=None):
        self.stack = Stack()
        self.max_stack = Stack()
        if data is not None:
            self.push(data)

    def push(self, data):
        self.stack.push(data)
        latest_max = self.max_stack.peek()
        if latest_max is not None:
            if latest_max.data[0] >= data:
                node = self.max_stack.pop()
                node_data = node.data
                node_data[1] += 1
                self.max_stack.push(node_data)
            else:
                self.max_stack.push([data, 1])
        else:
            self.max_stack.push([data, 1])

    def pop(self):
        popped_node = self.stack.pop()
        latest_max = self.max_stack.peek()
        if latest_max is not None:
            node = self.max_stack.pop()
            node_data = node.data
            node_data[1] -= 1
            if node_data[1] > 0:
                self.max_stack.push(node_data)
        return popped_node

    def max(self):
        latest_max = self.max_stack.peek()
        return latest_max.data[0]
class QueueOutOfStack:
    """Implements queue of two stacks.

    Idea:
        1st stack for input, 2nd for output.
        While enqueue is called, data is stored in the input stack
        Once dequeue is called it gets data from the output stack until
        it's empty. If dequeue is called on empty output stack,
        all data from input stack is flush to the output stack.

    """
    def __init__(self):
        self.input_stack = Stack()
        self.output_stack = Stack()

    def is_empty(self):
        return self.input_stack.is_empty() and self.output_stack.is_empty()

    def enqueue(self, item):
        self.input_stack.push(item)

    def dequeue(self):
        if self.output_stack.is_empty():
            while not self.input_stack.is_empty():
                self.output_stack.push(self.input_stack.pop())
        return self.output_stack.pop()
예제 #3
0
def parenthesesChecker(string):
    """
    Parentheses Checker validates the string using stack
    
    INPUT
    ---------
        string : '(()))'
    RETURN
    ---------
        Flag : False
    
    """
    temp = Stack(); balanceFlag = False
    
    for i in string:
        if i == "(":
            temp.push('i')
        if i == ")":
            if temp.isEmpty():
                balanceFlag = False
            else:
                temp.pop();
                balanceFlag = True
                
    if balanceFlag and temp.isEmpty():
        return True
    else:
        return False
예제 #4
0
def test_str():
    stk = Stack(3)
    stk.push(1)
    stk.push(2)
    stk.push(3)

    assert str(stk) == '3,2,1'
예제 #5
0
 def test_pop_from_populated_stack(self):
     """Pop a value from a populated stack."""
     s = Stack()
     s.push(self.single_value)
     popped = s.pop()
     self.assertEqual(popped, self.single_value)
     self.assertTrue(isinstance(popped, type(self.single_value)))
예제 #6
0
def test_iter():
    stack = Stack()
    stack.push("a")
    stack.push("b")
    stack.push("c")

    assert [item for item in stack] == ["c", "b", "a"]
예제 #7
0
def test_peek():
    s = Stack()
    s.push("apple")
    s.push("banana")
    actual = s.peek()
    expected = "banana"
    assert actual == expected
예제 #8
0
    def test_isEmpty(self):
        stack_empty = Stack()
        stack_full = Stack()
        stack_full.push('test')

        self.assertEqual(stack_empty.isEmpty(), True)
        self.assertEquals(stack_full.isEmpty(), False)
예제 #9
0
def test_pop():
    stack = Stack()
    stack.push("a")
    stack.push("b")

    assert stack.pop() == "b"
    assert len(stack) == 1
def toStr(n, base):
    """
    Convert given number to number in different base
    
    Instead of concatenating the result of the recursive call to toStr with the string 
    from stringMap, Push the strings onto a stack instead of making the recursive call
        
    INPUT
    -------
        n : Input number eg 1453
        base : base to convert the number to eg. 16 or Hexadecimal
    RETURN
    -------
        newStr = (1453,16) => 5AD
    """

    tempStack = Stack()
    stringMap = '0123456789ABCDEF'
    newStr = ''

    while (n > 0):
        quotient = n // base
        remainder = n % base
        if remainder > 9:
            tempStack.push(stringMap[remainder])
        else:
            tempStack.push(remainder)

        n = n // base

    while not tempStack.isEmpty():
        newStr += str(tempStack.pop())

    return newStr
예제 #11
0
 def test_push_to_empty_stack(self):
     """Push a value to an empty stack."""
     s = Stack()
     self.assertTrue(s.head is None)
     s.push(self.single_value)
     self.assertEqual(s.head.value, self.single_value)
     self.assertTrue(isinstance(s.head.value, type(self.single_value)))
예제 #12
0
def infix_to_postfix(expression):
    postfix = []
    priority = {'(': 1, '&': 2, '|': 2, '!': 2}
    operators = Stack()

    for token in expression:
        if token in OPERATORS:
            # Operators are added to the stack, but first the ones with a
            # higher priority are added to the result:
            while not operators.is_empty() and priority[token] <= priority[
                    operators.top()]:
                postfix.append(operators.pop())

            operators.push(token)

        # Left parenthesis are added to the stack:
        elif token == '(':
            operators.push(token)

        # Operators between parenthesis are added from the stack to the result:
        elif token == ')':
            while operators.top() != '(':
                postfix.append(operators.pop())

            operators.pop()  # Pop the left parentheses from the stack.

        # Operands are added to the result:
        else:
            postfix.append(token)

    while not operators.is_empty():
        # The remaining operators are added from the stack to the result:
        postfix.append(operators.pop())

    return postfix
예제 #13
0
def is_parentheses_balanced(input_string: str) -> bool:
    """Checks a string for balanced brackets of 3 different kinds: (),{},[].

    Args:
        input_string: a string to be checked

    Returns:
        True if parenthesis are balanced, False in other case

    """
    if input_string is None or not isinstance(input_string, str):
        raise ValueError('Incorrect input parameter! Shall be string')
    brackets_stack = Stack()
    par_dict = {'}': '{', ')': '(', ']': '['}
    for char in input_string:
        if char in par_dict.values():
            brackets_stack.push(char)
        elif char in par_dict.keys():
            last_element = brackets_stack.peek()
            if last_element == par_dict[char]:
                brackets_stack.pop()
            else:
                return False
        else:
            continue
    return brackets_stack.is_empty()
예제 #14
0
def test_stack_push_pop():
    el = 1
    stack = Stack(5)
    stack.push(el)

    assert stack.size() == 1
    assert stack.pop() == el
    assert stack.size() == 0
예제 #15
0
 def test_push_to_populated_stack(self):
     """Push a value to a populated stack."""
     s = Stack()
     self.assertTrue(s.head is None)
     for val in self.values:
         s.push(val)
     self.assertEqual(s.head.value, self.values[-1])
     self.assertTrue(isinstance(s.head.value, type(self.values[-1])))
예제 #16
0
def rev_string(test_str):
    string_stack = Stack()
    for ch in test_str:
        string_stack.push(ch)
    reverse_string = ''
    while not string_stack.isEmpty():
        reverse_string = reverse_string + string_stack.pop()
    return reverse_string
def rev_string(test_str):
	string_stack = Stack()
	for ch in test_str:
		string_stack.push(ch)
	reverse_string = ''
	while not string_stack.isEmpty():
		reverse_string = reverse_string + string_stack.pop()
	return reverse_string
예제 #18
0
    def test_pop_error(self):

        my_stack = Stack()
        my_stack.push(1)
        my_stack.push(2)
        my_stack.pop()
        my_stack.pop()
        self.assertRaises(Exception, my_stack.pop)
예제 #19
0
def _topological_sort(graph: Graph, vertex: Any, visited: Set, stack: Stack) -> None:
    visited.add(vertex)

    for neighbor in graph.adjacency_list[vertex]:
        if neighbor[0] not in visited:
            _topological_sort(graph, neighbor[0], visited, stack)

    stack.push(vertex)
예제 #20
0
def tower_of_hanoi(height=3, verbose=0):
    """
    Принцип работы:
    Задача разбивается на 3 этапа:
    1) Передвинуть все диски, кроме последнего с начального стержня на временный
    2) Передвинуть последний диск с начального стержня на конечный
    3) Передвинуть все диски с временного стержня на конечный
    Этап №1 - первый рекурсивный вызов
    Этап №2 - перемещение нижнего диска
    Этап №3 - второй рекурсивный вызов
    Таким образом, мы делаем ряд рекурсивных вызовов, до тех пор, пока нам не
    остается передвинуть всего один диск с from_pole на with_pole (base case).

    Так же хорошее пояснение можно почитать здесь
    http://www.cs.cmu.edu/~cburch/survey/recurse/hanoiimpl.html

        >>> tower_of_hanoi()
        >>> tower_of_hanoi(1)
        >>> tower_of_hanoi(0)

    :type height: int
    :type verbose: int
    """
    if verbose > 1:
        counter = Counter()
    initial_pole = Stack()
    for x in range(height, 0, -1):
        initial_pole.push(x)

    def print_poles_state(*poles):
        counter.increase()
        poles = sorted(poles, key=lambda pole: pole.id)
        print 'Poles after {0} move(s): {1}, {2}, {3}'.format(counter, *poles)

    def move_tower(height, from_pole, to_pole=Stack(),
                   with_pole=Stack()):
        """
        :type height: int
        :type from_pole: Stack
        :type to_pole: Stack
        :type with_pole: Stack
        """
        if height > 0:
            move_tower(height-1, from_pole=from_pole,
                       to_pole=with_pole, with_pole=to_pole)

            if verbose == 1:
                print "Moving disk from", from_pole, "to", to_pole

            to_pole.push(from_pole.pop())

            if verbose == 2:
                print_poles_state(from_pole, to_pole, with_pole)

            move_tower(height-1, from_pole=with_pole,
                       to_pole=to_pole, with_pole=from_pole)

    move_tower(height, initial_pole)
예제 #21
0
    def test_pop(self):
        stack = Stack()
        stack.push('win')
        stack.push('test')

        item = stack.pop()

        self.assertEqual(item, 'test')
        self.assertEqual(stack.head.data, 'win')
예제 #22
0
def test_stack():
    stack = Stack()
    stack.push("foo")
    stack.push("bar")
    stack.push("baz")

    assert "baz" == stack.pop()
    assert "bar" == stack.pop()
    assert "foo" == stack.pop()
예제 #23
0
def stack_reverse_string(input):
    stk = Stack()
    for elem in input:
        stk.push(elem)
    res = ""
    while stk.size() > 0:
        elem = stk.pop()
        res += elem
    return res
예제 #24
0
    def push(self, item):
        cur_stack = self.get_last_stack()
        if cur_stack and cur_stack.size < self.threshold:
            cur_stack.push(item)

        else:
            cur_stack = Stack()
            cur_stack.push(item)
            self.stack_set.append(cur_stack)
예제 #25
0
    def test_stack_length(self):
        #arrange
        my_stack = Stack()
        my_stack.push(1)
        my_stack.push(2)

        #assert
        self.assertEqual(2, len(my_stack),
                         "stack length does not return the correct length")
예제 #26
0
def test_pop(create_nodes, create_stack):
    n1, n2, n3 = create_nodes
    s = Stack()
    for ele in (n1, n2, n3):
        s.push(ele)
    assert s.head.next is n2
    assert s.pop() == n3.value
    assert s.head is n2
    assert s.head.next is n1
    assert n3.next is None
 def path_to(self, target: Vertex) -> Stack:
     if not self.initialized:
         print("Must be initialized first!")
         return
     if not self.has_path_to(target):
         return None
     path = Stack()
     current_vertex = target
     path.push(current_vertex)
     while (current_vertex := self.edge_to[current_vertex]) != self.source:
         path.push(current_vertex)
예제 #28
0
    def test_pop_item(self):
        stack = Stack()
        stack.push("item")

        assert len(stack) > 0
        assert len(stack) == 1

        value = stack.pop()

        assert value == "item"
        assert len(stack) == 0
        assert stack.peek() == None
예제 #29
0
    def test_push_peek(self):

        #Arrange
        my_stack = Stack()
        my_stack.push(1)
        my_stack.push(2)

        #Act
        peek = my_stack.peek()

        #Assert
        self.assertEqual(2, peek, "peek did not return expected value")
예제 #30
0
    def test_clear_stack(self):
        stack = Stack()
        stack.push("item1")
        stack.push("item2")
        stack.push("item3")

        assert len(stack) > 0
        assert len(stack) == 3

        stack.clear()

        assert len(stack) == 0
예제 #31
0
def test_pop():
    stk = Stack(0)
    with pytest.raises(IndexError):
        stk.pop()

    stk = Stack(3)
    stk.push(1)
    stk.push(2)
    stk.push(3)
    stk.pop()
    stk.pop()
    assert stk.head.data == 1
    assert stk.length == 1
def divide_by_2(dec_num):
	remstack = Stack()

	while dec_num > 0:
		rem = dec_num % 2
		remstack.push(rem)
		dec_num = dec_num // 2

	bin_string = ""
	while not remstack.isEmpty():
		bin_string = bin_string + str(remstack.pop())

	return bin_string
예제 #33
0
def all_nearest_smaller_values_v2(a):
    """Compute all nearest smaller values of array a using a Stack."""
    r = []
    s = Stack()
    for ix, x in enumerate(a):
        while not s.is_empty() and s.peek()[1] >= x:
            s.pop()
        if s.is_empty():
            r.append((None, None))  # (-1, None)
        else:
            r.append(s.peek())
        s.push((ix, x))
    return r
예제 #34
0
def divide_by_2(dec_num):
    remstack = Stack()

    while dec_num > 0:
        rem = dec_num % 2
        remstack.push(rem)
        dec_num = dec_num // 2

    bin_string = ""
    while not remstack.isEmpty():
        bin_string = bin_string + str(remstack.pop())

    return bin_string
예제 #35
0
    def test_push_len(self):

        #Arrange
        my_stack = Stack()
        my_stack.push(1)
        my_stack.push(2)
        my_stack.push(3)

        #Act
        length = my_stack.__len__()

        #Assert
        self.assertEqual(3, length, "len did not return correct length")
예제 #36
0
def is_palindrome(head: LinkedList) -> bool:
    current_node = head
    stack = Stack()

    while current_node:
        stack.push(current_node)
        current_node = current_node.next

    while head:
        if head.value != stack.pop().value:
            return False
        head = head.next
    return True
 def route_exists(self, node1, node2):
     """
     Returns whether a route exists between two nodes in the graph.
     """
     stack = Stack()
     for node in self.get_nodes():
         node.visited = False
     stack.push(node1)
     while not stack.is_empty():
         node = stack.pop()
         if node:
             for child in node.get_children():
                 if not child.visited:
                     if child is node2:
                         return True
                     else:
                         stack.push(child)
             node.visited = True
     return False
예제 #38
0
class testPop(unittest.TestCase):
    def setUp(self):
        self.stack = Stack()

    def testEmptyList(self):
        self.assertRaises(IndexError, self.stack.pop)

    def testListOfOne(self):
        self.stack = Stack(1)
        self.assertEqual(self.stack.pop().val, 1)
        self.stack.push("Hello")
        self.assertEqual(self.stack.pop().val, "Hello")

    def testLongList(self):
        self.stack = Stack(10, 11, 12, 13, 14)
        self.assertEqual(self.stack.pop().val, 14)
        self.assertEqual(self.stack.pop().val, 13)

    def tearDown(self):
        self.stack = None
예제 #39
0
 def depth_first_traversal(self, start):
     if start not in self.nodes():
         raise KeyError
     node = start
     stack = Stack()
     stack.push(node)
     traversed = []
     while len(traversed) < len(self.nodes()):
         try:
             node = stack.pop()
             print node
             traversed.insert(0, node)
             children = self.neighbors(node)
             for child in children:
                 if child not in traversed:
                    stack.push(child)
         except LookupError:
             break
     traversed.reverse()
     return traversed
예제 #40
0
파일: stack.py 프로젝트: richard-to/bscs
    def testStack(self):
        stack = Stack()
        self.assertTrue(stack.isEmpty())

        stack.push(5)
        self.assertFalse(stack.isEmpty())

        stack.clear()
        self.assertTrue(stack.isEmpty())

        stack.push(6)
        self.assertEqual(6, stack.top())
        self.assertEqual(6, stack.pop())
        self.assertTrue(stack.isEmpty())

        stack.push(7)
        stack.push(6)
        stack.push(5)
        self.assertEqual(5, stack.pop())
        self.assertEqual(6, stack.pop())
        self.assertEqual(7, stack.top())
예제 #41
0
class testPush(unittest.TestCase):
    def setUp(self):
        self.stack = Stack(10, 11, 12, 13, 14)

    def testEmpyList(self):
        self.stack = Stack()
        self.stack.push(10)
        self.assertEqual(self.stack.head.val, 10)

    def testListOfOne(self):
        self.stack = Stack()
        self.stack.push(10)
        self.stack.push(11)
        self.assertEqual(self.stack.head.val, 11)

    def testLongList(self):
        self.stack.push(15)
        self.assertEqual(self.stack.head.val, 15)
예제 #42
0
class TestStack(unittest.TestCase):

    def test_push_to_empty(self):
        self.my_stack = Stack()
        self.my_stack.push(5)
        self.assertEqual(5, self.my_stack.top.val)

    def test_push_to_non_empty(self):
        self.my_stack = Stack()
        self.my_stack.push(5)
        self.my_stack.push(4)
        self.assertEqual(4, self.my_stack.top.val)

    def test_pop_from_non_empty(self):
        self.my_stack = Stack()
        self.my_stack.push(5)
        self.assertEqual(5, self.my_stack.pop())

    def test_pop_from_empty(self):
        self.my_stack = Stack()
        self.failureException("Uh oh!!  You're trying to pop from an empty \
            stack", self.my_stack.pop())
예제 #43
0
def test_push(items):
    s = Stack()
    for item in items:
        s.push(item)
    for item in reversed(items):
        assert s.pop() == item
예제 #44
0
"""Docstring."""
from data_structures.stack import Stack
from data_structures.queue import Queue

q = Queue()
s = Stack()

s.push(4)
print(s)
예제 #45
0
class BTree(object):
    def __init__(self, degree=2):
        self.root = Node()
        self.stack = Stack()
        if degree < 2:
            raise InvalidDegreeError
        self.degree = degree

    def __repr__(self):
        """For printing out the tree and its nodes
        It's here to save me typing during debugging"""
        result = ''
        for i in self._bft():
            result += i
        return result

    def _bft(self):
        import queue
        keeper = queue.Queue()
        keeper.enqueue(self.root)
        while keeper.size() > 0:
            temp = keeper.dequeue()
            yield str(temp)
            if temp is not '\n' and temp.children[0]:
                keeper.enqueue('\n')
                for nod in temp.children:
                    if nod is not None:
                        keeper.enqueue(nod)

    def search(self, key):
        """Returns the value of the searched-for key"""
        nod, idx = self._recursive_search(self.root, key)
        return nod.elems[idx][1]

    def _recursive_search(self, node, key):
        """Searches the subtree for a specific key and returns
        where to find it if it is found
        If it is not found, raises a custom error"""
        # The index of the node in which the key is found
        idx = 0
        while idx <= node.count - 1 and key > node.elems[idx][0]:
            # Look to the next key in the node
            idx += 1
        if idx <= node.count - 1 and key == node.elems[idx][0]:
            # Found the key in the node
            return node, idx
        if not node.children[0]:
            raise MissingError
        else:
            # Look to the appropriate child
            return self._recursive_search(node.children[idx], key)

    def insert(self, key, val):
        """Inserts a key-value pair into the tree"""
        self._recursive_insert(self.root, key, val)

    def _split_child(self, parent, child):
        new = Node()
        for i in xrange(self.degree-1):
            new.add_to_node(*child.elems[i+self.degree])
            child.del_from_node(i+self.degree)
        parent.add_to_node(*child.elems[self.degree-1])
        child.del_from_node(self.degree-1)
        if child.children[0]:
            for i in xrange(self.degree):
                new.children[i], child.children[i+self.degree] = \
                    child.children[i+self.degree], None
            child.sort_children
        parent.children[2*self.degree-1] = new
        parent.sort_children()
        if parent.count == 2 * self.degree - 1:
            self._split_child(self.stack.pop().val, parent)

    def _recursive_insert(self, node, key, val):
        if not node.children[0]:
            node.add_to_node(key, val)
            if node.count == 2 * self.degree - 1:
                if node is self.root:
                    new = Node()
                    new.children[0], self.root = self.root, new
                    self.stack.push(new)
                self._split_child(self.stack.pop().val, node)
        else:
            self.stack.push(node)
            idx = node.count - 1
            while idx >= 0 and key < node.elems[idx][0]:
                idx -= 1
            self._recursive_insert(node.children[idx+1], key, val)


    def delete(self, key):
        self._recursive_delete(self.root, key)

    def _recursive_delete(self, node, key):
        pass

    def _move_key(self, key, src, dest):
        pass

    def _merge_nodes(self, node1, node2):
        pass