实用程序.py
import heapq
class PriorityQueue:
def __init__(self):
self.heap=[]
def push(self,item,priority):
pair = (priority,item)
heapq.heappush(self.heap,pair)
def pop(self):
(priority,item) = heapq.heappop(self.heap)
return item
def getHeap(self):
return self.heap
Class PriorityQueueWithFunction(PriorityQueue):
def __init__ (self,priorityFunction):
self.priorityFunction = priorityFunction
PriorityQueue.__init__(self)
def push(self,item):
PriorityQueue.push(self, item, self.priorityFunction(item))
pqtest.py
import os,sys
lib_path = os.path.abspath('../../lib/here')
sys.path.append(lib_path)
import Util
import string
import random
def str_gen():
return ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(random.randint(2,8)))
def pqfunc(item):
return len(str(item))
rdy = Util.PriorityQueueFunction(pqfunc)
for i in range(1,10):
rdy.push(str_gen())
for i in rdy.getHeap():
print i
它打印了
(3, '2UA')
(4, '6FD6')
(6, 'DLB66A') <---out of place
(4, 'J97K')
(7, 'GFQMRZZ') <----out of place
(6, 'SRU5T4')
(7, 'BP4PGKH')
(7, 'CBUJWQO')
(7, '5KNNY1P')
为什么这两个不合适,如何解决?
rdy.pop()
当我在里面 添加打印for i in rdy.getHeap():
时,当我推入 9 时,它只会弹出 5 个