Python uses list to implement a non-marginal priority queue (based on class, including iterator)

Source: Internet
Author: User
Tags python list

Python uses list to implement a non-marginal priority queue (based on class, including iterator)

#!/usr/bin/python # -*- coding: utf-8 -*-'''Created on 2015-2-4@author: beyondzhou@name: test_listpriorityqueue.py'''def test_listpriorityqueue():        # import pyListQueue    from myqueue import ListPriorityQueue        print '#Init a queue named smith using enqueue'    smith = ListPriorityQueue()    smith.enqueue('purple', 5)    smith.enqueue('black', 1)    smith.enqueue('orange', 3)    smith.enqueue('white', 0)    smith.enqueue('green', 1)    smith.enqueue('yellow', 5)            print '#output smith queue'    for element in smith:        print element               print '#dequeue one item'    smith.dequeue()        print '#output smith after dequeue'    for element in smith:        print element             print '#dequeue another item'    smith.dequeue()        print '#output smith after dequeue another item'    for element in smith:        print element             print '#get the length of queue'    print 'the lenght of queue is ', len(smith)        print '#check wheter the queue is empty'    if smith.isEmpty():        print 'stack is empty!'    else:        print 'stack is not empty!'            print '#dequeue all items'    while not smith.isEmpty():        smith.dequeue()        print '#check wheter the queue is empty after dequeue all items'    if smith.isEmpty():        print 'stack is empty!'    else:        print 'stack is not empty!'    if __name__ == __main__:    test_listpriorityqueue()

# Implementation of the unbounded Priority Queue ADT using a Python list# with new items appended to the endclass ListPriorityQueue:    # Create an empty unbounded priority queue    def __init__(self):        self._qList = list()    # Returns True if the queue is empty    def isEmpty(self):        return len(self) == 0    # Returns the number of items in the queue    def __len__(self):        return len(self._qList)    # Adds the given item to the queue    def enqueue(self, item, priority):        # Create a new instance of the storage class and append it to the list        entry = _ListPriorityQEntry(item, priority)        self._qList.append(entry)    # Removes and returns the first item in the queue    def dequeue(self):        assert not self.isEmpty(), Cannot dequeue from an empty queue.                # Find the entry with the highest priority        highest = self._qList[0].priority        index = 0        for i in range(self.__len__()):            # See if the ith entry contains a higher priority (smaller integer).            if self._qList[i].priority < highest:                highest = self._qList[i].priority                index = i                        # Remove the entry with the highest priority and return the item        entry = self._qList.pop(index)                    return entry.item    # Returns the array queue's iterator for traversing the elements    def __iter__(self):        return _ListPriorityQueueIterator(self._qList)# Private storage class for associating queue items with their priorityclass _ListPriorityQEntry(object):    def __init__(self, item, priority):        self.item = item        self.priority = priority# Implementation of iterclass _ListPriorityQueueIterator:    def __init__(self, theList):        self._setItems = theList        self._curItem = 0    def __iter__(self):        return self    def next(self):        if self._curItem < len(self._setItems):            item = self._setItems[self._curItem]            self._curItem += 1            return item.item, item.priority        else:            raise StopIteration

#Init a queue named smith using enqueue#output smith queue('purple', 5)('black', 1)('orange', 3)('white', 0)('green', 1)('yellow', 5)#dequeue one item#output smith after dequeue('purple', 5)('black', 1)('orange', 3)('green', 1)('yellow', 5)www.bkjia.com#dequeue another item#output smith after dequeue another item('purple', 5)('orange', 3)('green', 1)('yellow', 5)#get the length of queuethe lenght of queue is  4#check wheter the queue is emptystack is not empty!#dequeue all items#check wheter the queue is empty after dequeue all itemsstack is empty!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.