Ejemplo n.º 1
0
def run_stack():
    s = MyStack()
    s.push(5)
    v = s.pop()
    result = v == 5
    print("valid push/pop?: {}".format(result))
    try:
        s.pop()
    except StopIteration as e:
        print('correct exception throw')
Ejemplo n.º 2
0
 def __init__(self, size=10):
     self.push_stack = MyStack(size=size)
     self.pop_stack = MyStack(size=size)
Ejemplo n.º 3
0
class MyStackQueue(object):
    """
    :description: queue implemented with stacks

    :time: O(1) amortized time, O(n) worst case though. This is because each element will be enqueued and dequeued twice. If you add all elements to the push stack first and then pop them, then you can get O(n) time on dequeue, though enqueue will always be O(1)
    :space: O(n) because need each stack to hold entirety of queue
    """
    
    def __init__(self, size=10):
        self.push_stack = MyStack(size=size)
        self.pop_stack = MyStack(size=size)

    def enqueue(self, val):
        if self.is_full():
            raise OverflowError

        self.push_stack.push(val)

    def dequeue(self):
        if self.is_empty():
            raise StopIteration

        if self.pop_stack.is_empty():
            while not self.push_stack.is_empty():
                self.pop_stack.push(self.push_stack.pop())
        return self.pop_stack.pop()

    def is_empty(self):
        return self.push_stack.is_empty() and self.pop_stack.is_empty()

    def is_full(self):
        return self.push_stack.is_full() or self.pop_stack.is_full()