Queue1 -using two stacks impliment

# -*-coding: utf-8 -*-
# Author :writen by Qiusheng Li
# Time: 2014/08/18
# Email:[email protected]
# enqueue Insert an item at the back of the queue
# dequeue Remove an item from the front of the queue
# peek/front Retrieve an item at front of the queue without removing it
# empty/size Check whether the queue is empty or return its size
# using list impliment the Queue

#node we have learned that the method of insert for lists in python
#is very inefficient ,because when we append or pop at /from their
#end is only work on O(1),insert will shift all the other element.

class Queue(object):
    '''using two stacks impliemnt queue'''
    def __init__(self):
        self.initems = []
        self.outitems = []
        
    def enqueue(self,value):
        self.initems.append(value)
        
    def dequeue(self):
        if self.outitems != []: #not null   good job is if self.outitems:
            return self.outitems.pop()
        while self.initems:    # this is same upside
            self.outitems.append(self.initems.pop())
        if self.outitems:
             return self.outitems.pop()
        else:
             raise Exception('Queue is empty')
            
    def peek(self):
        if self.outitems: #not null good job is if self.outitems:
            return self.outitems[-1]
        while self.initems:    # this is same upside
            self.outitems.append(self.initems.pop())
        if self.outitems:
             return self.outitems[-1]
        else:
             raise Exception('Queue is empty')
            
    def isEmpty(self):
        return not (self.outitems and self.initems)
    def size(self):
        return len(self.initems) + len(self.outitems)

def Queue1Main():
    queue = Queue()
    queue.enqueue(1)
    queue.enqueue(2)
    queue.enqueue(3)
    print "size :   ",queue.size()
    print "peek:    ",queue.peek()
    print "dequeue: ",queue.dequeue()
    queue.enqueue(4)
    print "size :   ",queue.size()
    print "peek:    ",queue.peek()
    print "dequeue: ",queue.dequeue()
    print "dequeue: ",queue.dequeue()
    print "dequeue: ",queue.dequeue()
    print "dequeue: ",queue.dequeue()
'''testing result
size :    3
peek:     1
dequeue:  1
size :    3
peek:     2
dequeue:  2
dequeue:  3
dequeue:  4
dequeue: 

Traceback (most recent call last):
  File "F:/201408/project/technoloybook/algorithms/codes/Queue1.py", line 66, in 
    Queue1Main()
  File "F:/201408/project/technoloybook/algorithms/codes/Queue1.py", line 63, in Queue1Main
    print "dequeue: ",queue.dequeue()
  File "F:/201408/project/technoloybook/algorithms/codes/Queue1.py", line 32, in dequeue
    raise Exception('Queue is empty')
Exception: Queue is empty
'''
if __name__ == '__main__':
    Queue1Main()
    
        
        



你可能感兴趣的:(Python)