def validate_string(string):
    stack = Stack()

    # opening symbols
    opening = '{[('
    # closing symbols, must be in the matched order of opening
    closing = '}])'

    # iterate through the string we are testing
    for char in string:
        # if we encounter an opening symbol, push it to the stack
        if char in opening:
            stack.push(char)
        # if we encounter a closing symbol, check if it matches the top of the stack
        elif char in closing:
            i = closing.index(char)
            if stack.is_empty() or stack.pop() != opening[i]:
                return False

    # if we've not matched all the symbols... fail!
    if not stack.is_empty:
        return False

    # we have matched all the symbols, success!
    return True
def test_check_not_empty():
    s = Stack()
    s.push("apple")
    s.push("banana")
    actual = s.is_empty()
    expected = False
    assert actual == expected
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
Exemple #4
0
def test_pop_till_empty():
    stack = Stack()
    stack.push('Dwight')
    stack.push('Michael')
    stack.push('Jim')
    stack.pop()
    stack.pop()
    stack.pop()
    actual = stack.is_empty()
    expected = True
    assert actual == expected
Exemple #5
0
class PsuedoQueue:
    """
    This is a queue being implement using stack's
    push, pop and peek methods rather than having
    its own attributes and methods
    """
    def __init__(self):
        self.front_stack = Stack()
        self.rear_stack = Stack()
        # this is strictly here so that we may pass a test,
        self.front = None

    def peek(self):
        return self.front_stack.peek()

    def is_empty(self):
        return self.front_stack.is_empty()

    def enqueue(self, value=None):
        node = Node(value)
        if self.rear_stack.top:
            self.rear_stack.top.next = node
        self.rear_stack.top = node
        if not self.front_stack.top:
            self.front_stack.top = node
            # next line is solely here to pass a test
            self.front = self.front_stack.top

    def dequeue(self):
        # if the queue only holds one node, we must manually set the rear to None
        if (self.rear_stack.top == self.front_stack.top):
            self.rear_stack.top = None
        value = self.front_stack.pop()
        # next line is solely here to pass a test
        self.front = self.front_stack.top
        return value
Exemple #6
0
def test_empty_stack():
    stack = Stack()
    assert stack.is_empty()