Python 使用list实现无边际优先队列 (基于class, 包含迭代器)

#!/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 '\n#output smith queue'
    for element in smith:
        print element

    print '\n#dequeue one item'
    smith.dequeue()

    print '\n#output smith after dequeue'
    for element in smith:
        print element 

    print '\n#dequeue another item'
    smith.dequeue()

    print '\n#output smith after dequeue another item'
    for element in smith:
        print element 

    print '\n#get the length of queue'
    print 'the lenght of queue is ', len(smith)

    print '\n#check wheter the queue is empty'
    if smith.isEmpty():
        print 'stack is empty!'
    else:
        print 'stack is not empty!'

    print '\n#dequeue all items'
    while not smith.isEmpty():
        smith.dequeue()

    print '\n#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 end
class 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 priority
class _ListPriorityQEntry(object):
    def __init__(self, item, priority):
        self.item = item
        self.priority = priority

# Implementation of iter
class _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)

#dequeue another item

#output smith after dequeue another item
('purple', 5)
('orange', 3)
('green', 1)
('yellow', 5)

#get the length of queue
the lenght of queue is  4

#check wheter the queue is empty
stack is not empty!

#dequeue all items

#check wheter the queue is empty after dequeue all items
stack is empty!

时间: 2024-10-22 22:34:23

Python 使用list实现无边际优先队列 (基于class, 包含迭代器)的相关文章

Python 使用由单链表构建的数组实现有边际优先队列 (基于class, 包含迭代器)

#!/usr/bin/python # -*- coding: utf-8 -*- ''' Created on 2015-2-6 @author: beyondzhou @name: test_bpriorityqueue.py ''' def test_bpriorityqueue(): # import pyListQueue from myqueue import BPriorityQueue print '#Init a queue named smith using enqueue'

Python 使用list实现堆栈 (基于class, 包含迭代器)

#!/usr/bin/python # -*- coding: utf-8 -*- ''' Created on 2015-1-27 @author: beyondzhou @name: test_liststack.py ''' def test_liststack(): # import listStack from mystack import listStack print '#Init a stack named smith using push' smith = listStack(

Python 使用循环数组实现队列 (基于class, 包含迭代器)

#!/usr/bin/python # -*- coding: utf-8 -*- ''' Created on 2015-2-2 @author: beyondzhou @name: test_arryqueue.py ''' def test_arryqueue(): # import pyListQueue from myqueue import arrayQueue print '#Init a queue named smith using enqueue' smith = array

Python 使用list实现队列 (基于class, 包含迭代器)

#!/usr/bin/python # -*- coding: utf-8 -*- ''' Created on 2015-1-27 @author: beyondzhou @name: test_listqueue.py ''' def test_listqueue(): # import pyListQueue from myqueue import pyListQueue print '#Init a queue named smith using enqueue' smith = pyL

Python 使用单链表实现堆栈 (基于class, 包含迭代器)

#!/usr/bin/python # -*- coding: utf-8 -*- ''' Created on 2015-1-28 @author: beyondzhou @name: test_linkliststack.py ''' def test_linkliststack(): # import linkListStack from mystack import LinkListStack print '#Init a stack named smith using push' sm

Python 使用单链表实现队列 (基于class, 包含迭代器)

#!/usr/bin/python # -*- coding: utf-8 -*- ''' Created on 2015-2-3 @author: beyondzhou @name: test_linklistqueue.py ''' def test_linklistqueue(): # import pyListQueue from myqueue import linkListQueue print '#Init a queue named smith using enqueue' sm

【机器学习算法-python实现】K-means无监督学习实现分类

1.背景 无监督学习的定义就不多说了,不懂得可以google.因为项目需要,需要进行无监督的分类学习. K-means里面的K指的是将数据分成的份数,基本上用的就是算距离的方法. 大致的思路就是给定一个矩阵,假设K的值是2,也就是分成两个部分,那么我们首先确定两个质心.一开始是找矩阵每一列的最大值max,最小值min,算出range=max-min,然后设质心就是min+range*random.之后在逐渐递归跟进,其实要想明白还是要跟一遍代码,自己每一步都输出一下看看跟自己想象的是否一样. (

Python:SQLMap源码精读之基于时间的盲注(time-based blind)

基于时间的盲注(time-based blind) 测试应用是否存在SQL注入漏洞时,经常发现某一潜在的漏洞难以确认.这可能源于多种原因,但主要是因为Web应用未显示任何错误,因而无法检索任何数据. 对于这种情况,要想识别漏洞,向数据库注入时间延迟并检查服务器响应是否也已经延迟会很有帮助.时间延迟是一种很强大的技术,Web服务器虽然可以隐藏错误或数据,但必须等待数据库返回结果,因此可用它来确认是否存在SQL注入.该技术尤其适合盲注. 源码解释 代码位置:在checkSqlInjection函数中

通过python获取kvm虚拟机的监控信息(基于libvirt API)

通常在我们的云环境中,为了保证云平台中虚拟机的正常运行,基本都需要这样一个功能,就是收集虚拟机的监控数据,比如cpu的使用率.内存的使用率.磁盘io.网络io等基本信息.可以利用这些信息及时调整云平台环境中出现的一些问题,从而实现保证VM的正常运行. 说到KVM管理工具,首先应该想到的就是libvirt,因为目前对KVM使用最为广泛的管理工具(应用程序接口)就是libvirt.Libvirt本身构建于一种抽象的概念上,它为受支持的虚拟机监控程序实现常用功能提供通用的API.Libvirt提供了操