示例#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]
示例#2
0
def test_peek_empty_stack():
    stack = Stack()

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

    assert str(exc.value) == "peek from empty list"
示例#3
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
示例#4
0
def test_peek():
    stk = Stack(5)
    stk.push(0)
    stk.push(1)
    stk.push(2)
    stk.push(3)
    stk.push(4)

    with pytest.raises(IndexError):
        stk.peek(5)

    assert stk.peek(0) == 0
    assert stk.peek(2) == 2
    assert stk.peek(4) == 4
示例#5
0
    def test_push(self):
        stack = Stack()

        stack.push(1)
        self.assertEqual(stack.peek(), 1)

        stack.push(50)
        self.assertEqual(stack.peek(), 50)

        stack.push(30)
        self.assertEqual(stack.peek(), 30)

        stack.push(70)
        self.assertEqual(stack.peek(), 70)
示例#6
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()
示例#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_peek():
    stack = Stack()
    stack.push("a")
    stack.push("b")

    assert stack.peek() == "b"
    assert len(stack) == 2
示例#9
0
def test_change():
    stk = Stack(5)
    stk.push(0)
    stk.push(1)
    stk.push(2)
    stk.push(3)
    stk.push(4)

    with pytest.raises(IndexError):
        stk.change(5, 5)

    stk.change(1, -1)
    stk.change(2, -2)
    stk.change(4, -4)
    assert stk.peek(1) == -1
    assert stk.peek(2) == -2
    assert stk.peek(4) == -4
示例#10
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")
示例#11
0
    def test_pop(self):
        stack = Stack()
        stack.push(1)
        stack.push(50)
        stack.push(30)
        stack.push(70)

        self.assertEqual(stack.pop(), 70)
        self.assertEqual(stack.pop(), 30)

        stack.push(75)
        self.assertEqual(stack.peek(), 75)

        self.assertEqual(stack.pop(), 75)
        self.assertEqual(stack.pop(), 50)

        stack.push(876)
        self.assertEqual(stack.peek(), 876)

        self.assertEqual(stack.pop(), 876)
        self.assertEqual(stack.pop(), 1)
示例#12
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
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()
示例#14
0
class TestStack(TestCase):
    def setUp(self):
        super().setUp()
        self.stack = Stack()

    def test_pop(self):
        self.stack.push(1)
        self.stack.push(2)

        self.assertEqual(self.stack.pop(), 2)
        self.assertEqual(self.stack.pop(), 1)

    def test_pop_empty(self):
        self.assertIsNone(self.stack.pop())

    def test_peek(self):
        self.stack.push(1)
        self.stack.push(2)

        self.assertEqual(self.stack.peek(), 2)
        self.stack.pop()
        self.assertEqual(self.stack.peek(), 1)

    def test_size(self):
        self.stack.push(1)
        self.stack.push(2)

        self.assertEqual(self.stack.size(), 2)

    def test_is_empty(self):
        self.assertTrue(self.stack.is_empty())

        self.stack.push(1)

        self.assertFalse(self.stack.is_empty())

        self.stack.pop()
def is_balanced(symbols):
    """
    >>> is_balanced('([{}])')
    True
    >>> is_balanced('([]{}())')
    True
    >>> is_balanced('((()))')
    True
    >>> is_balanced('(([{])')
    False
    >>> is_balanced('[}([){]')
    False
    >>> is_balanced('[')
    False
    """
    if not isinstance(symbols, str):
        raise TypeError('symbols must be a string')

    if len(symbols) == 0:
        raise ValueError('symbols must have at least one symbol')

    stack = Stack()
    for symbol in symbols:
        if stack.is_empty():
            stack.push(symbol)
        else:
            top_symbol = stack.peek()
            if allowed_symbols.get(top_symbol, None) == symbol:
                stack.pop()
            else:
                stack.push(symbol)

    if stack.is_empty():
        return True

    return False
示例#16
0
def test_peek_empty():
    s = Stack()
    with pytest.raises(InvalidOperationError) as e:
        s.peek()

    assert str(e.value) == "Method not allowed on empty collection"
示例#17
0
from data_structures.stack import Stack

size = int(input("Enter the size of the stack: "))
stack = Stack(size)

while True:
    choice = int(input("Enter your choice [0 - show menu]: "))

    if choice == 0:
        print("1. Push element")
        print("2. Pop element")
        print("3. Peek element")
        print("4. Display all elements")
        print("Any other number to exit")
    elif choice == 1:
        element = input("Enter the element to push: ")
        stack.push(element)
    elif choice == 2:
        element = stack.pop()
        if element is not None:
            print("Element popped is:", element)
    elif choice == 3:
        element = stack.peek()
        if element is not None:
            print("Top element is:", element)
    elif choice == 4:
        stack.display()
    else:
        print("Exited")
        break
示例#18
0
    def test_peek(self):
        stack = Stack()
        stack.push('test')

        self.assertEqual(stack.peek().data, 'test')
示例#19
0
    def test_peek_is_none(self):
        stack = Stack()

        with self.assertRaises(ValueError):
            stack.peek()
示例#20
0
from data_structures.stack import Stack

# creating a new stack
stack = Stack()

print('Pushing some values into the stack.')
stack.push('A')
stack.push('B')
stack.push('C')

print('Peeking into the stack.')
print(stack.peek())

print('Popping the values from the stack.')
print(stack.pop())
print(stack.pop())
print(stack.pop())
示例#21
0
    def test_push_item(self):
        stack = Stack()
        stack.push("item")

        assert len(stack) > 0
        assert stack.peek() == "item"