예제 #1
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)
예제 #2
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
예제 #3
0
def test_pop():
    stack = Stack()
    stack.push("a")
    stack.push("b")

    assert stack.pop() == "b"
    assert len(stack) == 1
예제 #4
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
예제 #5
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 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
예제 #7
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
예제 #8
0
def test_iter():
    stack = Stack()
    stack.push("a")
    stack.push("b")
    stack.push("c")

    assert [item for item in stack] == ["c", "b", "a"]
예제 #9
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()
예제 #10
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()
예제 #11
0
def test_peek():
    s = Stack()
    s.push("apple")
    s.push("banana")
    actual = s.peek()
    expected = "banana"
    assert actual == expected
예제 #12
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)
예제 #13
0
def test_str():
    stk = Stack(3)
    stk.push(1)
    stk.push(2)
    stk.push(3)

    assert str(stk) == '3,2,1'
예제 #14
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
예제 #15
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
예제 #16
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)
예제 #17
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
예제 #18
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
예제 #19
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()
예제 #20
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)
예제 #21
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")
예제 #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 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)
예제 #24
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')
예제 #25
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
예제 #26
0
    def test_init(self):
        stack = Stack([6, 8, 45, 1, 84, 149, 9, 17])

        self.assertEqual(stack.pop(), 17)
        self.assertEqual(stack.pop(), 9)
        self.assertEqual(stack.pop(), 149)
        self.assertEqual(stack.pop(), 84)
        self.assertEqual(stack.pop(), 1)
        self.assertEqual(stack.pop(), 45)
        self.assertEqual(stack.pop(), 8)
        self.assertEqual(stack.pop(), 6)
 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_push():
    stk = Stack(0)
    with pytest.raises(IndexError):
        stk.push(5)

    stk = Stack(3)
    stk.push(1)
    assert stk.head.data == 1

    stk.push(2)
    assert stk.head.data == 2
    assert stk.head.next.data == 1

    stk.push(3)
    assert stk.head.data == 3
    assert stk.head.next.data == 2
    assert stk.head.next.next.data == 1

    with pytest.raises(IndexError):
        stk.push(4)
예제 #29
0
def test_pop_until_empty():
    s = Stack()
    s.push("apple")
    s.push("banana")
    s.push("cucumber")
    s.pop()
    s.pop()
    s.pop()
    actual = s.is_empty()
    expected = True
    assert actual == expected
예제 #30
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")