def stack_test(source):
    """
    -------------------------------------------------------
    Tests the methods of Stack for empty and 
    non-empty stacks using the data in source:
    is_empty, push, pop, peek
    (Testing pop and peek while empty throws exceptions)
    Use: stack_test(source)
    -------------------------------------------------------
    Parameters:
        source - list of data (list of ?)
    Returns:
        None
    -------------------------------------------------------
    """
    stack = Stack()
    print('Test is empty?')
    print(stack.is_empty())
    print(array_to_stack(stack, source))
    print('Test is empty?')
    print(stack.is_empty())
    print('Test for peek value: ')
    print(stack.peek())
    print('Test for push value: ')
    stack.push(1)
    print('Test for peek value: ')
    print(stack.peek())
    print('Test for pop value: ')
    stack.pop()
    print('Test is empty?')
    print(stack.is_empty())
    print('Test for peek value: ')
    print(stack.peek())
예제 #2
0
def stack_test(source):
    """
    -------------------------------------------------------
    Tests the methods of Stack for empty and 
    non-empty stacks using the data in source:
    is_empty, push, pop, peek
    (Testing pop and peek while empty throws exceptions)
    Use: stack_test(source)
    -------------------------------------------------------
    Parameters:
        source - list of data (list of ?)
    Returns:
        None
    -------------------------------------------------------
    """
    s = Stack()

    print("Stack Initialised")
    print()
    print(SEP)
    print("Stack is_empty (expect True): {}".format(s.is_empty()))
    print(SEP)
    print("Add one item to Stack:")
    s.push(source[0])
    print("Top of Stack (peek):")
    print(s.peek())
    print(SEP)
    print("Stack is_empty (expect False): {}".format(s.is_empty()))
    print(SEP)
    print("Stack pop:")
    v = s.pop()
    print(v)
    print(SEP)
    print("Stack is_empty (expect True): {}".format(s.is_empty()))
    print(SEP)
    print("Copy all data to Stack")
    array_to_stack(s, source)
    print(SEP)
    print("Stack is_empty (expect False): {}".format(s.is_empty()))
    print(SEP)
    print("Top of Stack (peek):")
    print(s.peek())
    print(SEP)
    print("Remove all elements from Stack")

    while not s.is_empty():
        v = s.pop()
        print(v)
        print()

    print(SEP)
    print("Stack is_empty (expect True): {}".format(s.is_empty()))
    print()
    return
예제 #3
0
def has_balanced_brackets(string):
    """
    -------------------------------------------------------
    Determines if a string contains balanced brackets or not. Non-bracket
    characters are ignored. Uses a stack. Brackets include {}, [], (), <>.
    Use: balanced = has_balanced_brackets(string)
    -------------------------------------------------------
    Parameters:
        string - the string to test (str)
    Returns:
        balanced (int) -
            BALANCED if the brackets in string are balanced
            MISMATCHED if the brackets in string are mismatched
            MORE_RIGHT if there are more right brackets than left in string
            MORE_LEFT if there are more left brackets than right in string
    -------------------------------------------------------
    """
    right = 0
    left = 0

    s = Stack()

    for x in string:
        if s.is_empty() == True:
            s.push(x)
        elif s.peek() == '[' and x == ']' or s.peek(
        ) == '(' and x == ')' or s.peek() == '{' and x == '}' or s.peek(
        ) == '<' and x == '>':
            s.pop()
        else:
            s.push(x)

    if s.is_empty() == True:
        balanced = 0
    else:
        while s.is_empty() == False:
            x = s.pop()
            if x == '(' or x == '[' or x == '{' or x == '<':
                left += 1
            elif x == ')' or x == ']' or x == '}' or x == '>':
                right += 1
        if right > left:
            balanced = 2
        elif left > right:
            balanced = 1
        else:
            balanced = 3

    return balanced
예제 #4
0
def stack_test(source):
    """
    -------------------------------------------------------
    Tests the methods of Stack for empty and 
    non-empty stacks using the data in source:
    is_empty, push, pop, peek
    (Testing pop and peek while empty throws exceptions)
    Use: stack_test(source)
    -------------------------------------------------------
    Parameters:
        source - list of data (list of ?)
    Returns:
        None
    -------------------------------------------------------
    """
    s = Stack()
    
    # Test if stack is empty (Expected: TRUE)
    print("Stack contents: ")
    for i in s:
        print(i, end=' ')
    print("\tEmpty? {}".format(s.is_empty()))
    # Load elements from source into Stack
    print(">> Push elements from source onto stack")
    print(">> Num elements to push: {}".format(len(source)))    
    for elem in source:
        s.push(elem)
    
    # Check if the Stack is empty again (T/F depending on source contents)
    print("Stack contents: ")
    for i in s:
        print(i, end=' ')
    print("\tEmpty? {}".format(s.is_empty()))
    # Peek the top of the stack
    top = None
    try:
        top = s.peek()
    except:
        print(">>! Peeked at an empty stack, assertion caught, continuing...")
    # Check if top of stack is the end element of source
    print("Top of stack should be same as end of list")
    if s.is_empty():
        print("List empty so no check")
    else:
        top_same = top == source[-1]
        print("Top same as end of list?")
        print("Top: {}\tEnd of list: {}".format(top, source[-1]))
        print("Same? {}".format(top_same))
    
    # Testing pop
    try:
        print(">> Pop top of stack")
        popped = s.pop()
        print("Popped value should be same as end of list.\tSame? {}".format(popped == source[-1]))
    except:
        print(">>! Popped from an empty stack, exception caught, continuing...")
    return
예제 #5
0
def stack_test(source):
    """
    -------------------------------------------------------
    Tests the methods of Stack for empty and 
    non-empty stacks using the data in source:
    is_empty, push, pop, peek
    (Testing pop and peek while empty throws exceptions)
    Use: stack_test(source)
    -------------------------------------------------------
    Parameters:
        source - list of data (list of ?)
    Returns:
        None
    -------------------------------------------------------
    """
    stack = Stack()
    dummy = []
    if stack.is_empty() == True:
        print('Stack is empty.')

    array_to_stack(stack, source)
    print('Converting source into a stack...')

    if stack.is_empty() == False:
        print('source has been transferred into stack!')

    print('\nPopping stack...')
    while stack.is_empty() == False:
        temp = stack.pop()
        print(temp)
        dummy.append(temp)

    print('\nstack is empty. Pushing values back into stack...')
    while dummy != []:
        temp = dummy.pop()
        print(temp)
        stack.push(temp)

    print('\nPushing complete! Peeking...')
    print(stack.peek())

    return
예제 #6
0
def stack_test(source):
    """
    -------------------------------------------------------
    Tests the methods of Stack for empty and
    non-empty stacks using the data in source:
    is_empty, push, pop, peek
    (Testing pop and peek while empty throws exceptions)
    Use: stack_test(source)
    -------------------------------------------------------
    Parameters:
        source - list of data (list of ?)
    Returns:
        None
    -------------------------------------------------------
    """
    s = Stack()
    array_to_stack(s, source)
    print(s.is_empty())
    print(s.peek())
    print(s.pop())
    s.push(1)
    return
예제 #7
0
from Stack_array import Stack

values = [1, 2, 3, 4]

print("Values: {}".format(values))

s = Stack()

print(">> Is the stack empty?")
empty = s.is_empty()

print("Expect: {}\tGot: {}".format(True, empty))

print(">> Pushing values onto Stack")

for val in values:
    s.push(val)

print("Stack contents: ", end='')
print("Expect: {}\tGot: ".format(values[::-1]), end='')
for elem in s:
    print(elem, end=' ')
print()
print(">> Pop top of stack")
value = s.pop()
print("Expect: {}\tGot: {}".format(values[-1], value))

print(">> Peek the top of the stack")
peeked = s.peek()
print("Expect: {}\tGot: {}".format(values[-2], peeked))
예제 #8
0
"""
------------------------------------------------------------------------
Lab 2, Task 2 - utilities#array_to_stack
------------------------------------------------------------------------
Author: Nicolas Mills
ID:     180856100
Email:  [email protected]
__updated__ = 2019-01-21
------------------------------------------------------------------------
"""
from utilities import array_to_stack
from Stack_array import Stack

array = [0, 1, 2, 3, 4]
s = Stack()

print("Array: {}".format(array))

array_to_stack(s, array)

print("Values: {}".format(s._values))
print("Stack to Array: ")
for elem in s:
    print(elem, end=' ')
print()
print("Array: {}".format(array))

print("Top: {}".format(s.peek()))