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'
    smith = BPriorityQueue(6)
    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:
        for i in element:
            print i

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

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

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

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

    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_bpriorityqueue()
from myarray import Array

# Implementation of the bounded Priority Queue ADT using an array of
# queues in which the queues are implemented using a linked list
#from myarray import Array
class BPriorityQueue:
    # Creates an empty bounded priority queue
    def __init__(self, numLevels):
        self._qSize = 0
        self._numLevels = numLevels
        self._qLevels = Array(numLevels)
        for i in range(numLevels):
            self._qLevels[i] = linkListQueue()

    # 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 self._qSize

    # Adds the given item to the queue
    def enqueue(self, item, priority):
        assert priority >= 0 and priority < len(self._qLevels),                     "Invalid priority level."
        self._qLevels[priority].enqueue(item)
        self._qSize += 1

    # Removes and returns the next item in the queue
    def dequeue(self):
        # Make sure the queue is not empty
        assert not self.isEmpty(), "Cannot dequeue from an empty queue."
        # Find the first non-empty queue
        i = 0
        p = len(self._qLevels)
        while i < p:
            if not self._qLevels[i].isEmpty():
                break
            i += 1
        # We know the queue is not empty, so dequeue from the ith queue
        self._qSize -= 1
        return self._qLevels[i].dequeue()

    # Returns the array queue's iterator for traversing the elements
    def __iter__(self):
        return _BPriorityQueueIterator(self._qLevels)

# Implementation of iter
class _BPriorityQueueIterator:
    def __init__(self, qLevels):
        self._qLevels = qLevels
        self._curItem = 0
    def __iter__(self):
        return self
    def next(self):
        items = []
        if self._curItem < len(self._qLevels):
            for i in self._qLevels[self._curItem]:
                items.append(i)
            self._curItem += 1
            return items
        else:
            raise StopIteration
#Init a queue named smith using enqueue

#output smith queue
white
black
green
orange
purple
yellow

#dequeue one item

#output smith after dequeue
black
green
orange
purple
yellow

#dequeue another item

#output smith after dequeue another item
green
orange
purple
yellow

#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-08-30 07:51:06

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

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

python实现数据结构单链表

#python实现数据结构单链表 # -*- coding: utf-8 -*- class Node(object): """节点""" def __init__(self, elem): self.elem = elem self.next = None # 节点一开始初始化的时候并不知道下一个元素的地址,所以先设置为空 class SingLinkList(object): """单链表""

Python线性表——单链表

1. 线性表简介 线性表是一种线性结构,它是由零个或多个数据元素构成的有限序列.线性表的特征是在一个序列中,除了头尾元素,每个元素都有且只有一个直接前驱,有且只有一个直接后继,而序列头元素没有直接前驱,序列尾元素没有直接后继. 数据结构中常见的线性结构有数组.单链表.双链表.循环链表等.线性表中的元素为某种相同的抽象数据类型.可以是C语言的内置类型或结构体,也可以是C++自定义类型. 2. 数组 数组在实际的物理内存上也是连续存储的,数组有上界和下界.C语言中定义一个数组: 数组下标是从0开始的

Python 之简易单链表

单链表的基本要素有 2 个,数据项和连接项.这两项在 Python 中可以通过对象及其属性来实现. 1 class Node: 2 def __init__ (self, data): 3 self.data = data 4 self.next = None 5 6 def add (self, data): 7 p = self 8 9 while p.next != None: 10 p = p.next 11 12 p.next = Node (data) 13 14 def subtr

python中的单链表实现

引子 数据结构指的是是数据的组织的方式.从单个数据到一维结构(线性表),二维结构(树),三维结构(图),都是组织数据的不同方式. 为什么需要链表? 顺序表的构建需要预先知道数据大小来申请连续的存储空间,而在进行扩充时又需要进行数据的搬迁,所以使用起来并不是很灵活. 链表结构可以充分利用计算机内存空间,实现灵活的内存动态管理. 链表(Linked list)是一种常见的基础数据结构,是一种线性表,但是不像顺序表一样连续存储数据,而是在每一个节点(数据存储单元)里存放下一个节点的位置信息(即地址).

python数据结构之单链表

单链表的操作 1.is_empty()链表是否为空 2.length()链表的长度 3.add()链表的头部添加元素 4.append()链表尾部添加元素 5.insert()指定位置添加元素 6.remove()删除节点 7.search()查找链表是否存在 源代码 class Node(): """节点""" def __init__(self,data = None): self.elem = data #节点中的数据 self.next

python——数据结构之单链表的实现

链表的定义: 链表(linked list)是由一组被称为结点的数据元素组成的数据结构,每个结点都包含结点本身的信息和指向下一个结点的地址.由于每个结点都包含了可以链接起来的地址 信息,所以用一个变量就能够访问整个结点序列.也就是说,结点包含两部分信息:一部分用于存储数据元素的值,称为信息域:另一部分用于存储下一个数据元素 地址的指针,称为指针域.链表中的第一个结点的地址存储在一个单独的结点中,称为头结点或首结点.链表中的最后一个结点没有后继元素,其指针域为空. #!/usr/bin/pytho

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