0 Replies - 1595 Views - Last Post: 09 May 2012 - 07:48 AM

#1 atraub   User is offline

  • Pythoneer
  • member icon

Reputation: 830
  • View blog
  • Posts: 2,251
  • Joined: 23-December 08

Queue Class

Posted 09 May 2012 - 07:48 AM

Description: if you create a Queue with no parameters, it's empty. myQueue = Queue() if you create a Queue with an iterable value as its parameter, it will convert that iterable in the default python way. myList = [1,2,3,4,5] myQueue = Queue(myList) you can also create a Queue with comma separated values as the parameter. myQueue = Queue("I","like","potato","chips")This is a full featured Queue class that uses proper naming conventions in accordance with the abstract data type "Stack". It also utilizes proper error handling.
__author__ = "atraub"
__date__= "5/9/2012"

class Queue:
    """Implements a basic queue class in Python using a list"""
    def __init__(self, *elements):
        """intializes a queue, elements allow you to include elements in queue constructor"""
        #allows a list or tuple to be converted into a queue
        if len(elements) == 1:
                test = iter(elements[0]) #check if the only element is iterable
                self.__queue = list(elements[0])#if it is, make it into a queue
            except TypeError as e:
                self.__queue = list(elements)#if not, put it in the queue
            self.__queue = list(elements)
    def enqueue(self,element):
        """add element to the end of the queue"""
    def dequeue(self):
        """remove and return front element from queue"""
        if len(self.__queue) == 0:
            raise IndexError("dequeue from empty queue")
        return self.__queue.pop(0)
    def front(self):
        """view front element of queue"""
        if len(self.__queue) == 0:
            raise IndexError("can't view front element of empty queue")
        return self.__queue[0]

    def isEmpty(self):
        """returns true if queue is empty"""
        return len(self.__queue) == 0

    def hasMore(self):
        """returns true if queue is not empty"""
        return len(self.__queue) != 0

    def clear(self):
        """empties the queue"""
        self.__queue = []

    def __len__(self):
        """returns the length of the queue"""
        return len(self.__queue)

    def __str__(self):
        """returns a string representation of a queue for printing"""
        return str(self.__queue)

    def __repr__(self):
        """creates a string representation of a queue"""
        return repr(self.__queue)

    def __add__(self,iterable):
        """overloads the + operator for adding iterables to queues"""
        return Queue(self.__queue + (list(iterable)))

    def __iter__(self):
        """gets an iterator for a queue"""
        return iter(self.__queue)

Is This A Good Question/Topic? 1
  • +

Page 1 of 1