예제 #1
0
 def test_size(self):
     # test if the size is being enforced
     stack = Stack(size=10)
     for num in range(1000):
         stack.push(num)
     assert stack.size() == 10
     assert stack.stack == [_ for _ in range(10)]
예제 #2
0
def dummyFunc(opcode: Opcode, bytecode: bc.Bytecode, stack: st.Stack):

    if opcode.consume > 0:
        stack.pop(opcode.consume, type_hint_constants.ANY)

    if opcode.produce > 0:
        import time
        stack.push(str(int(time.time())))
예제 #3
0
def dummyFunc(opcode: Opcode, bytecode: bc.Bytecode, stack: st.Stack):

    if opcode.consume > 0:
        stack.pop(opcode.consume, type_hint_constants.ANY)

    if opcode.produce > 0:
        import time
        stack.push(str(int(time.time())))
 def test_size(self):
     s = Stack(10)
     s.push(10)
     s.push(20)
     assert s.size == 2
     s.pop()
     s.pop()
     assert s.size == 0
예제 #5
0
def test_push():
    """Test push."""
    s = Stack()
    s.push(3)
    s.push(5)
    s.push(7)
    assert len(s.data) == 3
    assert not s.is_empty()
예제 #6
0
def test_push_empty_stack():
    stack = Stack()
    element = 230
    stack.push(element)

    expected = [230]
    output = stack.stack
    assert output == expected
 def test_push(self):
     s = Stack(10)
     s.push(10)
     assert s.top.value == 10
     assert s.top.next == None
     s.push(20)
     assert s.top.value == 20
     assert s.top.next.value == 10
 def validate_brackets(sentence):
     brackets = Stack()
     for char in sentence:
         if char == '(':
             brackets.push(True)
         elif char == ')':
             if brackets.pop() is not True:
                 return False
     return brackets.size() == 0
    def test_exceptions(self):
        with self.assertRaises(StackUnderflowException):
            s = Stack(1)

            s.pop()
        with self.assertRaises(StackOverflowException):
            s = Stack(1)

            s.push(10)
            s.push(20)
예제 #10
0
    def test_pop(self):
        s = Stack()

        value = s.pop()
        self.assertIsNone(value, 'should return None from empty stack')

        s.push(1)
        value = s.pop()
        self.assertEqual(value, 1, 'should return the stack value')
        self.assertEqual(s.pop(), None, 'should remain an empty stack')
예제 #11
0
파일: test_stack.py 프로젝트: mindis/learn
    def test_pop(self):
        s = Stack()

        value = s.pop()
        self.assertIsNone(value, 'should return None from empty stack')

        s.push(1)
        value = s.pop()
        self.assertEqual(value, 1, 'should return the stack value')
        self.assertEqual(s.pop(), None, 'should remain an empty stack')
 def test_pop(self):
     s = Stack(10)
     s.push(20)
     s.push(10)
     value = s.pop()
     assert value == 10
     assert s.top.value == 20
     assert s.top.next == None
     s.pop()
     assert s.top == None
예제 #13
0
    def test_push(self):
        s = Stack()

        s.push(1)
        self.assertEqual(s.top['value'], 1, 'should have inserted 1')
        self.assertIsNone(s.top['prev'], 'should have nothing before')

        s.push(2)
        self.assertEqual(s.top['value'], 2, 'should have 2 as top')
        self.assertEqual(s.top['prev']['value'], 1, 'should have 1 before')
        self.assertIsNone(s.top['prev']['prev'], '1 is the last value')
예제 #14
0
파일: test_stack.py 프로젝트: mindis/learn
    def test_push(self):
        s = Stack()

        s.push(1)
        self.assertEqual(s.top['value'], 1, 'should have inserted 1')
        self.assertIsNone(s.top['prev'], 'should have nothing before')

        s.push(2)
        self.assertEqual(s.top['value'], 2, 'should have 2 as top')
        self.assertEqual(s.top['prev']['value'], 1, 'should have 1 before')
        self.assertIsNone(s.top['prev']['prev'], '1 is the last value')
예제 #15
0
def test():
    s = Stack()
    assert s.is_empty() is True

    s.push(4)
    assert s.items == [4]

    s.push("dog")
    assert s.items == [4, "dog"]

    assert s.peek() == "dog"

    s.push(True)
    assert s.items == [4, "dog", True]

    assert s.size() == 3

    assert s.is_empty() is False

    s.push(8.4)
    assert s.items == [4, "dog", True, 8.4]

    assert s.pop() == 8.4

    assert s.pop() is True

    assert s.size() == 2
예제 #16
0
def sort_stack(stack):
    buffer_stack = Stack()
    while(not stack.is_empty()):
        value = stack.pop()
        if(buffer_stack.is_empty):
            buffer_stack.push(value)
        else:
            if(not buffer_stack.is_empty()):
                while(buffer_stack.peek() > value):
                        temp = buffer_stack.pop()
                        stack.push(temp)
            else:
                buffer_stack.push(value)
    return buffer_stack
예제 #17
0
    def test_stack_empty(self):
        stack = Stack()
        self.assertTrue(stack.empty())

        stack.push(1)
        self.assertFalse(stack.empty())

        stack.push(2)
        self.assertEqual(stack.__str__(), "Stack[2, 1]")
        self.assertFalse(stack.empty())

        stack.clear()

        self.assertTrue(stack.empty())
예제 #18
0
class CalculatorTest(unittest.TestCase):
    """unitetestモジュールの簡単な実行例その2。"""
    @classmethod
    def setUpClass(cls):
        pass

    @classmethod
    def tearDownClass(cls):
        pass

    def setUp(self):
        self._stack = Stack()

    def tearDown(self):
        pass

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

        self._stack.push(1)
        self.assertFalse(self._stack.is_empty())

    def test_size(self):
        self.assertEqual(0, self._stack.size())

        self._stack.push(1)
        self.assertEqual(1, self._stack.size())

    def test_push(self):
        self._stack.push(1)
        self.assertEqual(1, self._stack.top())

    def test_pop(self):
        self._stack.push(1)
        self.assertEqual(1, self._stack.pop())
        self.assertEqual(0, self._stack.size())

        with self.assertRaises(IndexError):
            self._stack.pop()

    def test_top(self):
        self._stack.push(1)
        self.assertEqual(1, self._stack.top())
        self.assertEqual(1, self._stack.size())

        self._stack.pop()
        with self.assertRaises(IndexError):
            self._stack.top()
예제 #19
0
파일: test_stack.py 프로젝트: mindis/learn
    def test_len(self):
        s = Stack()
        self.assertEqual(len(s), 0, 'no elements yet')

        s.push(1)
        self.assertEqual(len(s), 1, 'one element')

        s.push(2)
        self.assertEqual(len(s), 2, 'two elements')

        s.pop()
        self.assertEqual(len(s), 1, 'one element left')

        s.pop()
        self.assertEqual(len(s), 0, 'no elements left')

        s.pop()
        self.assertEqual(len(s), 0, 'still no elements left')
예제 #20
0
    def test_len(self):
        s = Stack()
        self.assertEqual(len(s), 0, 'no elements yet')

        s.push(1)
        self.assertEqual(len(s), 1, 'one element')

        s.push(2)
        self.assertEqual(len(s), 2, 'two elements')

        s.pop()
        self.assertEqual(len(s), 1, 'one element left')

        s.pop()
        self.assertEqual(len(s), 0, 'no elements left')

        s.pop()
        self.assertEqual(len(s), 0, 'still no elements left')
예제 #21
0
def proper_parens(str):
    """Return 0 if string of parens is balanced, 1 if open and -1 if broken."""
    stack = Stack()

    for i in str:

        if i is '(':
            stack.push(i)
            print('data', stack._container.head.data)
        elif i is ')':
            try:
                stack.pop()
            except IndexError:
                return -1

    if stack._container.head:
        return 1

    return 0
예제 #22
0
def testStack():
    '''
    Here we test algorithms for stacks
    We test pushing, popping, and checking if 
    a stack is empty

    Stack is implemented as a python list
    It's not the best implementation as we'll
    show that the stack will be empty yet it 
    will be occupying memory with the previously 
    inserted elements
    '''

    print('Create an empty stack')
    s = Stack()
    print('Pop now')
    print('Topmost element: ' + str(s.pop()))
    print('Insert 5')
    s.push(5)
    print('Insert 3')
    s.push(3)
    print('Insert 4')
    s.push(4)
    print('Is stack empty: ' + str(s.isempty()))
    print('Position of top: ' + str(s.top))
    print('Pop now')
    print('Topmost element: ' + str(s.pop()))
    print('Pop now')
    print('Topmost element: ' + str(s.pop()))
    print('Pop now')
    print('Topmost element: ' + str(s.pop()))
    print('Pop now')
    print('Topmost element: ' + str(s.pop()))
    print('Stack in the memory')
    print(s.storage)
예제 #23
0
class TestStack(unittest.TestCase):
    def setUp(self):
        self.stack = Stack()

    def tearDown(self):
        del self.stack

    def test_push_pop_peek(self):
        values = [10, 20, 30, 40, 50]
        for value in values:
            self.stack.push(value)

        self.assertEqual(len(values), self.stack.size())
        values.reverse()
        for value in values:
            self.assertEqual(value, self.stack.peek())
            self.assertEqual(value, self.stack.pop())

    def test_pop(self):
        self.stack.push(10)
        self.assertEqual(1, self.stack.size())
        self.assertEqual(10, self.stack.pop())
        self.assertEqual(0, self.stack.size())

    def test_peek(self):
        self.stack.push(10)
        self.assertEqual(1, self.stack.size())
        self.assertEqual(10, self.stack.peek())
        self.assertEqual(1, self.stack.size())

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

    def test_peek_empty(self):
        self.assertIsNone(self.stack.peek())
    def expr_to_stack(self, expr):
        stack = Stack()

        buf = ''
        idx = len(expr) - 1
        while idx >= 0:
            char = expr[idx]
            idx -= 1

            # If 0-9 then add to buffer (for multi-digit numbers)
            if char.isdigit():
                buf = char + buf
                continue

            # Convert value from buffer to integer and move to stack
            if buf != '':
                stack.push(int(buf))
                buf = ''

            # Add operators to stack
            if not char.isdigit() and char in self.allowed_operators.keys():
                stack.push(char)

        # Finally flush buffer into stack
        if buf != '':
            stack.push(int(buf))

        return stack
예제 #25
0
class TestStack(unittest.TestCase):
    def setUp(self):
        self.stack = Stack()

    def tearDown(self):
        self.stack = None

    def test_push(self):
        self.stack.push("foo")
        self.assertTrue(self.stack.stack.head.data == "foo")
        self.assertTrue(self.stack.stack.head.next is None)

        self.stack.push("bar")
        self.assertTrue(self.stack.stack.head.data == "bar")
        self.assertTrue(self.stack.stack.head.next.data == "foo")

    def test_pop(self):
        self.stack.push("foo")
        self.stack.push("bar")

        self.assertTrue(self.stack.stack.head.data == "bar")
        self.assertTrue(self.stack.stack.head.next.data == "foo")
        
        self.stack.pop()
        self.assertTrue(self.stack.stack.head.data == "foo")
        self.assertTrue(self.stack.stack.head.next is None)
예제 #26
0
def calculate_span(stock_price: list):
    if len(stock_price) == 0:
        raise ValueError("The list cannot be an empty list")

    if not isinstance(stock_price, list):
        raise ValueError("The `stocks_prices` must be a list")

    if not all([isinstance(i, int) for i in stock_price]):
        raise ValueError("All values must be integers")

    s = Stack(len(stock_price) + 1)
    s.push(0)
    span = [0] * len(stock_price)
    for idx, i in enumerate(stock_price):
        while not s.empty() and stock_price[s.top.value] <= i:
            v = s.pop()
        if (s.empty()):
            span[idx] = idx + 1
        else:
            span[idx] = idx - s.top.value
        s.push(idx)
    return span
예제 #27
0
def test_push_with_multiple_elements():
    stack = Stack()
    stack.push([1, 2, 3])
    stack.push("Horse")
    stack.push(9.321)

    expected = [[1, 2, 3], "Horse", 9.321]
    output = stack.stack
    assert output == expected
    def calculate(self, expr):
        result = Stack()
        elements = self.expr_to_stack(expr)

        while elements.size() > 0:
            element = elements.pop()

            # If passed operator "=", then we return value from result buffer
            if element == '=':
                return result.pop()

            # If passed number, then add it to result buffer
            if isinstance(element, int):
                result.push(element)

            # If passed another operator, then calculate
            if element in self.allowed_operators:  # If size >= 2
                y = result.pop()
                x = result.pop()
                value = self.allowed_operators[element](
                    x, y)  # Pass params in reverted direction
                result.push(value)

        return result.pop()
예제 #29
0
    def generate(self, z, sample, max_length):
        """Generate a valid expression from z using the decoder"""
        logits_all = self.decoder(z, max_length=max_length).squeeze()
        rules_all = []
        for logits in logits_all:
            t = 0
            stack = Stack(grammar=GCFG, start_symbol=START)
            rules = []
            while stack.nonempty:
                alpha = stack.pop()
                print(alpha)
                mask = get_mask(alpha, stack.grammar, as_variable=True)
                probs = mask * logits[t].exp()
                probs = probs / probs.sum()
                if sample:
                    m = Categorical(probs)
                    i = m.sample()
                else:
                    _, i = probs.max(-1)  # argmax
                # convert PyTorch Variable to regular integer
                i = i.item()
                # select rule i
                rule = stack.grammar.productions()[i]
                rules.append(rule)
                # add rhs nonterminals to stack in reversed order
                for symbol in reversed(rule.rhs()):
                    if isinstance(symbol, Nonterminal):
                        stack.push(symbol)
                t += 1
                if t == max_length:
                    break
            rules_all.append(rules)
        # if len(rules) < 15:
        #     pad = [stack.grammar.productions()[-1]]

        return rules_all
예제 #30
0
    def test_stack_pop_top(self):
        stack = Stack()

        self.assertTrue(stack.empty())

        stack.push(1)
        self.assertFalse(stack.empty())
        self.assertEqual(stack.top(), 1)

        stack.push(2)
        self.assertEqual(stack.top(), 2)

        stack.push(3)
        self.assertEqual(stack.top(), 3)
        self.assertEqual(stack.__str__(), "Stack[3, 2, 1]")

        self.assertEqual(stack.pop(), 3)

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

        self.assertEqual(stack.pop(), 1)
        self.assertTrue(stack.empty())
예제 #31
0
def test_peek():
    """Test peek."""
    s = Stack()
    s.push(3)
    assert s.peek() == 3
예제 #32
0
def test_pop():
    """Test pop."""
    s = Stack()
    s.push(3)
    assert s.pop() == 3
예제 #33
0
from src.stack import Stack


def sort_stack(stack):
    buffer_stack = Stack()
    while(not stack.is_empty()):
        value = stack.pop()
        if(buffer_stack.is_empty):
            buffer_stack.push(value)
        else:
            if(not buffer_stack.is_empty()):
                while(buffer_stack.peek() > value):
                        temp = buffer_stack.pop()
                        stack.push(temp)
            else:
                buffer_stack.push(value)
    return buffer_stack


if __name__ == "__main__":
    stack = Stack()
    values = [2, 7, 3, 5, 8, 2, 10, 4, 5, 11, 1]
    for value in values:
        stack.push(value)
    print(stack.items)
    sorted_stack = sort_stack(stack)
    print(sorted_stack.items)
예제 #34
0
    def filter_tokens(self):
        """
        Requests tokens from the lexer and adds INDENT and DEDENT
        to the stream where relevant.

        :return: filtered token
        :raise: VykingIndentationError
        """
        # Vyking has 3 indentation states.
        # - no colon hence no need to indent
        # - COLON was read, next rule must be a single line statement
        #   or a block statement
        # - NEWLINE was read after a colon, user must indent
        BOF = 0  # Beginnig of file
        NO_INDENT = 1
        MAY_INDENT = 2  # COLON was read
        MUST_INDENT = 3  # COLON and NEWLINE were read

        # Stack storing indentation levels met
        levels = Stack()
        levels.push(0)

        state = BOF

        # helper function
        def need_DEDENT(token):
            """Returns True if DEDENT is needed"""
            if token.value > levels.read():
                raise VykingIndentationError(
                    token.lineno,
                    "indentation level is too high.\n"
                    " \tHint: check for missing colon or mismatch in indentation level.",
                )
            else:
                return token.value < levels.read()

        for token in self.lexer:
            # ignore NEWLINEs at beginning of input
            if state == BOF:
                if token.type == "NEWLINE":
                    continue
                else:
                    state = NO_INDENT

            if state == NO_INDENT:
                if token.type == "COLON":
                    state = MAY_INDENT
                    yield token
                elif token.type == "WS":
                    while need_DEDENT(token):
                        levels.pop()
                        yield self._DEDENT(token.lineno - 1)
                else:
                    yield token

            elif state == MAY_INDENT:
                if token.type == "NEWLINE":
                    state = MUST_INDENT
                else:
                    state = NO_INDENT
                yield token

            else:  # MUST_INDENT
                if token.type == "WS" and token.value > levels.read():
                    # Store new indentation level
                    levels.push(token.value)
                    state = NO_INDENT
                    yield self._INDENT(token.lineno)
                else:
                    raise VykingIndentationError(token.lineno, "Expected indentation")

        # Yield DEDENTs at end of input
        while levels.pop() != 0:
            yield self._DEDENT(self.get_lineno())

        yield self._new_token("ENDMARKER", self.get_lineno())
        yield None
예제 #35
0
def pushFunc(opcode: Opcode, bytecode: bc.Bytecode, stack: st.Stack):
    toPush = bytecode.read(opcode.getShift())
    if len(toPush) == 0:
        raise ExceptionalHalt("No values to push in bytecode sequence")
    stack.push(toPush)
예제 #36
0
class TestStack(unittest.TestCase):
    def setUp(self) -> None:
        self.stack = Stack()

    def test_pop(self) -> None:
        self.stack.stack = [1]
        self.assertEqual(self.stack.pop(), 1)
        self.assertEqual(self.stack.stack, [])
        self.stack.stack = []
        self.assertIsNone(self.stack.pop())
        self.assertEqual(self.stack.stack, [])
        self.stack.stack = [1, 2, 3]
        self.assertEqual(self.stack.pop(), 3)
        self.assertEqual(self.stack.stack, [1, 2])

    def test_push(self) -> None:
        self.stack.push(1)
        self.assertEqual(self.stack.stack, [1])
        self.stack.push(2.0)
        self.assertEqual(self.stack.stack, [1, 2.0])
        self.stack.push("3")
        self.assertEqual(self.stack.stack, [1, 2.0, "3"])

    def test_peek(self) -> None:
        self.assertIsNone(self.stack.peek())
        self.stack.stack = [1]
        self.assertEqual(self.stack.peek(), 1)
        self.stack.stack = [1, 2, 3]
        self.assertEqual(self.stack.peek(), 3)
        self.assertEqual(self.stack.stack, [1, 2, 3])

    def test_search(self) -> None:
        self.assertIsNone(self.stack.search(1))
        self.stack.stack = [1]
        self.assertEqual(self.stack.search(1), 1)
        self.stack.stack = [1, 2, 3]
        self.assertEqual(self.stack.search(1), 3)
        self.assertEqual(self.stack.search(2), 2)
        self.assertEqual(self.stack.search(3), 1)

    def test_is_empty(self) -> None:
        self.assertTrue(self.stack.is_empty())
        self.stack.stack = [1]
        self.assertFalse(self.stack.is_empty())
        self.stack.stack = [1, 2, 3]
        self.assertFalse(self.stack.is_empty())

    def test_clear(self) -> None:
        self.stack.stack = [1, 2, 3]
        self.stack.clear()
        self.assertEqual(self.stack.stack, [])

    def test___str__(self) -> None:
        self.stack.stack = [1, 2, 3]
        self.assertEqual(self.stack.__str__(), "[1, 2, 3]")

    def test___len__(self) -> None:
        self.stack.stack = [1, 2, 3]
        self.assertEqual(len(self.stack), 3)

    def test_big_test(self) -> None:
        test_case = 100_000
        for i in range(test_case):
            self.stack.push(i)
        for i in reversed(range(test_case)):
            self.assertEqual(self.stack.pop(), i)
        self.assertIsNone(self.stack.pop())

    def test_repr(self) -> None:
        for i in range(6):
            self.stack.push(i)
        self.assertEqual(self.stack.__repr__(), "Stack [0, 1, 2, 3, 4, 5]")
        self.stack.push(6)
        self.assertEqual(self.stack.__repr__(),
                         "Stack [0, 1, 2, 3, 4, 5, ...]")