コード例 #1
0
def test_stack():
    """Fixture for testing."""
    from src.stack import Stack
    empty = Stack()
    one = Stack(5)
    multi = Stack([1, 2, 'three', 4, 5])
    return empty, one, multi
コード例 #2
0
def initialize_stack(num_disks):
    global stacks
    global left
    global middle
    global right
    global moves
    global inv_f
    global min_moves
    global final_answer
    global game_completion_f

    stacks = []
    left_stack = Stack("Left")
    middle_stack = Stack("Middle")
    right_stack = Stack("Right")

    stacks.append(left_stack)
    stacks.append(middle_stack)
    stacks.append(right_stack)

    for i in range(num_disks, 0, -1):
        stacks[0].push(i)

    left = stacks[0].get_items()
    middle = stacks[1].get_items()
    right = stacks[2].get_items()
    moves = 0
    inv_f = 0
    min_moves = 2**num_disks - 1
    game_completion_f = 0
    final_answer = left
コード例 #3
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)
コード例 #4
0
    def test_stack_exceptions(self):
        with self.assertRaises(ValueError):
            s = Stack("A")

        with self.assertRaises(ValueError):
            s = Stack(10)
            s.size = "A"

        with self.assertRaises(ValueError):
            s = Stack(10)
            s.top = "A"
コード例 #5
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)
コード例 #6
0
def test_openvpn_security_group():
    output = (Stack().template_to_json())
    properties = output["Resources"]["OpenVPNSecurityGroup"]["Properties"]

    expect(properties["GroupName"]).to.eq('OpenVPN')
    expect(properties["GroupDescription"]).to.eq(
        'This is a security group for OpenVPN')
    expect(properties["SecurityGroupIngress"]).to.eq([{
        "CidrIp": "0.0.0.0/0",
        "IpProtocol": "tcp",
        "FromPort": 22,
        "ToPort": 22
    }, {
        "CidrIp": "0.0.0.0/0",
        "IpProtocol": "udp",
        "FromPort": 1194,
        "ToPort": 1194
    }])
    expect(properties["SecurityGroupEgress"]).to.eq([{
        'CidrIp': '0.0.0.0/0',
        'FromPort': -1,
        'IpProtocol': -1,
        'ToPort': -1
    }])
    expect(properties["VpcId"]).to.eq(vpc_id)
コード例 #7
0
def test_openvpn_ec2_instance():
    output = (Stack().template_to_json())
    properties = output["Resources"]["EC2OpenVPN"]["Properties"]

    expect(properties["ImageId"]).to.eq('ami-0b69ea66ff7391e80')
    expect(properties["InstanceType"]).to.eq('t2.micro')
    expect(properties["KeyName"]).to.eq('rwalker')
コード例 #8
0
def test_pop_with_full_stack():
    stack = Stack([2, 4, 1, 4020])

    expected = 4020
    output = stack.pop()
    assert output == expected
    assert stack.stack[-1] == 1
コード例 #9
0
def test_print_empty_stack(capsys):
    stack = Stack()
    stack.print()

    expected = "[]\n"
    output = capsys.readouterr().out
    assert output == expected
コード例 #10
0
    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
コード例 #11
0
def test_peek_stack_with_elements():
    stack = Stack([1, 2, "Dog"])

    expected = "Dog"
    output = stack.peek()
    assert output == expected
    assert stack.stack[-1] == expected
コード例 #12
0
def test_print_stack_with_elements(capsys):
    stack = Stack([1, 2, 3, 4, 5])
    stack.print()

    expected = "[1, 2, 3, 4, 5]\n"
    output = capsys.readouterr().out
    assert output == expected
コード例 #13
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)]
コード例 #14
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
コード例 #15
0
 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
コード例 #16
0
def test_push_empty_stack():
    stack = Stack()
    element = 230
    stack.push(element)

    expected = [230]
    output = stack.stack
    assert output == expected
コード例 #17
0
 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
コード例 #18
0
ファイル: test_stack.py プロジェクト: chyld/captains-log
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()
コード例 #19
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
コード例 #20
0
 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
コード例 #21
0
 def __init__(self, text: str):
     # Data stack (main stack for operations).
     self.__ds = Stack()
     # Return stack (supports procedures work).
     self.__rs = Stack()
     # Instruction pointer.
     self.__iptr = 0
     # Input text parsed into list of values and instructions.
     self.__code_list = list(self.parse(text))
     # Storage for variables. Mapping names of vars to their values.
     self.__heap = dict()
     # Storage for procedures.
     self.__procedures = dict()
     # Mapping operations in our language to functions that perform the necessary business logic.
     self.__valid_operations = {
         '+': self.sum,
         '-': self.sub,
         '*': self.mult,
         '/': self.div,
         '%': self.mod,
         '!': self.fact,
         '==': self.equal,
         '>': self.greater,
         '<': self.less,
         'and': self.operator_and,
         'or': self.operator_or,
         'cast_int': self.cast_int,
         'cast_str': self.cast_str,
         'drop': self.drop,
         'over': self.over,
         'dup': self.dup,
         'if': self.operator_if,
         'jmp': self.jump,
         'stack': self.output_stack,
         'swap': self.swap,
         'print': self.print,
         'println': self.println,
         'read': self.read,
         'call': self.call,
         'return': self.ret,
         'exit': self.exit,
         'store': self.store,
         'load': self.load,
     }
コード例 #22
0
ファイル: test_stack.py プロジェクト: elverkilde/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')
コード例 #23
0
 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
コード例 #24
0
ファイル: test_stack.py プロジェクト: elverkilde/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')
コード例 #25
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
コード例 #26
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())
コード例 #27
0
ファイル: test_stack.py プロジェクト: elverkilde/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')
コード例 #28
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
コード例 #29
0
ファイル: provision.py プロジェクト: rwinfosec/openvpn-stack
def main():
    template = json.dumps(Stack().template_to_json())
    params = {'StackName': stack_name, 'TemplateBody': template}

    try:
        cf.validate_template(TemplateBody=template)
        if _stack_exists(stack_name):
            print('Updating {}'.format(stack_name))
            cf.update_stack(**params)
            waiter = cf.get_waiter('stack_update_complete')
        else:
            print('Creating {}'.format(stack_name))
            cf.create_stack(**params)
            waiter = cf.get_waiter('stack_create_complete')
        print("...waiting for stack to be ready...")
        waiter.wait(StackName=stack_name)
    except botocore.exceptions.ClientError as ex:
        error_message = ex.response['Error']['Message']
        if error_message == 'No updates are to be performed.':
            print("No changes")
        else:
            raise
コード例 #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())