示例#1
0
 def __init__(self, expression_in_infix_notation: str):
     """
     :param expression_in_infix_notation: string with expression in infix notation
     """
     self.expression_in_infix_notation = Queue_(expression_in_infix_notation)
     self.expression_in_postfix_notation = ReversePolishNotation()
     self.stack = Stack()
示例#2
0
def test_pop():
    stack = Stack()
    stack.push("a")
    stack.push("b")

    assert stack.pop() == "b"
    assert len(stack) == 1
class ReversePolishNotationConverterState:
    """
    Class to store the state of RPN convert process
    """
    def __init__(self, expression_in_infix_notation: str):
        """
        :param expression_in_infix_notation: string with expression in infix notation
        """
        self.expression_in_infix_notation = Queue_(
            expression_in_infix_notation)
        self.expression_in_postfix_notation = ReversePolishNotation()
        self.stack = Stack()

    def pop_from_stack_until_opening_bracket(self):
        """
        Help function помогает вытащить все из стека
        :return:
        """
        el = self.stack.top()
        while not isinstance(el, OpenBracket):
            self.expression_in_postfix_notation.put(el)
            self.stack.top()

        # выкнуть откр скобку из стека
        self.stack.pop()
 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)))
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()
 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)))
示例#7
0
def test_pop_empty_stack():
    stack = Stack()

    with pytest.raises(IndexError) as exc:
        stack.pop()

    assert str(exc.value) == "pop from empty list"
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 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])))
示例#10
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)
示例#11
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)
示例#12
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)
示例#13
0
    def __init__(self, expression_in_infix_notation: str):
        self.expression_in_infix_notation = Queue_(expression_in_infix_notation)
        self.expression_in_postfix_notation = ReversePolishNotation()
        self.stack = Stack()

        while not ReversePolishNotationConverter.is_open_bracket(self.stack.top()):
            self.expression_in_postfix_notation.put(self.stack.top())
            self.stack.pop()
        self.stack.pop()
示例#14
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")
示例#15
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
示例#16
0
class QueueStack:

    def __init__(self):
        self._stack1 = Stack()
        self._stack2 = Stack()

    def enqueue(self, item):
        """Add item to the enqueue stack.

        Parameters:
        item: item to add to the queue
        """
        while len(self._stack1) > 0:
            self._stack2.push(self._stack1.pop())
        self._stack2.push(item)

    def dequeue(self):
        """Remove item from the queue.

        Returns:
        item: First item in queue
        """
        while len(self._stack2) > 0:
            self._stack1.push(self._stack2.pop())
        return self._stack1.pop()
示例#17
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")
示例#18
0
def test_stack_push_overflows():
    stack = Stack(5)
    stack.push(1)
    stack.push(1)
    stack.push(1)
    stack.push(1)
    stack.push(1)
    with pytest.raises(StackOverflowError):
        assert stack.push(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
示例#20
0
 def depth_first_list(self):
     """returns a list created by traversing the tree in depth first manner"""
     li = []
     stack = Stack("bst")
     stack.push(self.root)
     while not stack.is_empty():
         node = stack.pop()
         li.append(node.data)
         if node.left:
             stack.push(node.left)
         if node.right:
             stack.push(node.right)
     return li
示例#21
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
示例#22
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
示例#23
0
    def test_push_pop(self):

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

        # Act
        pop1 = my_stack.pop()
        pop2 = my_stack.pop()

        # Assert
        self.assertEqual(2, pop1, "first pop did not have the expected value")
        self.assertEqual(1, pop2, "second pop did not have the expected value")
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
示例#25
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()
示例#26
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
示例#27
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)
示例#28
0
def test_push_onto_full():
    s = Stack()
    s.push("apple")
    s.push("banana")
    s.push("cucumber")
    actual = s.top.value
    expected = "cucumber"
    assert actual == expected
示例#29
0
def topological_sort(graph: Graph) -> None:
    visited = set()
    stack = Stack()
    for vertex in graph.adjacency_list:
        if vertex not in visited:
            _topological_sort(graph, vertex, visited, stack)
    print(stack)
示例#30
0
class QueueOfStacks(object):
    """A Queue using only Stacks as its underlying data stucture."""

    def __init__(self):
        """Initialize the Queue with two stacks holding data."""
        self._out_stack = Stack()
        self._in_stack = Stack()
        self._size = 0

    def enqueue(self, val):
        """Add an item to the Queue."""
        self._in_stack.push(val)
        self._size += 1

    def dequeue(self):
        """Remove the front item in the Queue and return it."""
        try:
            item = self._pop()
            self._size -= 1
            return item
        except IndexError:
            raise IndexError("Cannot dequeue from an empty Queue.")

    def peek(self):
        """Return the front item in the Queue without removing it."""
        try:
            item = self._pop()
            self._out_stack.push(item)
            return item
        except IndexError:
            return None

    def size(self):
        """Return the length of the Queue."""
        return self._size

    def _pop(self):
        """Pop item from out stack, transferring or raising error if needed."""
        try:
            item = self._out_stack.pop()
        except IndexError:
            self._transfer()
            item = self._out_stack.pop()
        return item

    def _transfer(self):
        """Transfer all items from the from_stack to the to_stack."""
        while True:
            try:
                self._out_stack.push(self._in_stack.pop())
            except IndexError:
                break
示例#31
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()
def postfix_calculator(expression: str) -> int:
    stack = Stack()
    for char in expression.split(" "):
        if char.isdigit():
            stack.push(int(char))
        else:
            # I'm assuming that user input is valid. In "real world" project
            # it's necessary to check if is a valid operator.
            right = stack.pop()
            left = stack.pop()
            result = eval(f"{left}{char}{right}")
            stack.push(result)

    return stack.peek()
示例#33
0
def test_peek():
    s = Stack()
    s.push("apple")
    s.push("banana")
    actual = s.peek()
    expected = "banana"
    assert actual == expected
示例#34
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
示例#35
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
示例#36
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')
示例#37
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
示例#38
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())
 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
示例#40
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)
 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
示例#42
0
 def testEmpyList(self):
     self.stack = Stack()
     self.stack.push(10)
     self.assertEqual(self.stack.head.val, 10)
示例#43
0
"""Docstring."""
from data_structures.stack import Stack
from data_structures.queue import Queue

q = Queue()
s = Stack()

s.push(4)
print(s)
示例#44
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
示例#45
0
 def __init__(self, degree=2):
     self.root = Node()
     self.stack = Stack()
     if degree < 2:
         raise InvalidDegreeError
     self.degree = degree
示例#46
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())
示例#47
0
 def setUp(self):
     self.stack = Stack()
示例#48
0
 def setUp(self):
     self.stack = Stack(10, 11, 12, 13, 14)
示例#49
0
 def test_pop_from_non_empty(self):
     self.my_stack = Stack()
     self.my_stack.push(5)
     self.assertEqual(5, self.my_stack.pop())
示例#50
0
 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)
示例#51
0
 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())
示例#52
0
 def test_push_to_empty(self):
     self.my_stack = Stack()
     self.my_stack.push(5)
     self.assertEqual(5, self.my_stack.top.val)
示例#53
0
 def testListOfOne(self):
     self.stack = Stack()
     self.stack.push(10)
     self.stack.push(11)
     self.assertEqual(self.stack.head.val, 11)
示例#54
0
def test_push(items):
    s = Stack()
    for item in items:
        s.push(item)
    for item in reversed(items):
        assert s.pop() == item
示例#55
0
def test_pop(items):
    s = Stack(items)
    for item in reversed(items):
        assert s.pop() == item
    with pytest.raises(IndexError):
        s.pop()
示例#56
0
 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")