用python的list物件實現最小堆的優先佇列

2021-09-17 05:18:23 字數 2104 閱讀 1350

class prio_queue(object):

"""docstring for prio_queue,最小堆優先佇列"""

def __init__(self, elems=):

self._elems = list(elems)

self.build_queue()

def clear_queue(self): #清除整個佇列

self._elems=

def get_head(self): #獲得佇列的第乙個元素,不改變佇列

if self.is_empty():

raise syntaxerror("the queue is empty")

return self._elems[0]

def queue_length(self): #返回佇列長度

return len(self._elems)

def is_empty(self): #返回佇列是否為空

if self.queue_length()>0:

return false

else:

return true

def enqueue(self,e): #插入乙個元素進佇列

index = len(self._elems)-1

self._adjust_up(index,e)

def dequeue(self): #取出佇列第乙個元素,並從佇列中刪除它

if self.is_empty():

raise syntaxerror("the queue is empty")

e0 = self._elems[0]

self._elems[0]=self._elems[-1]

self._elems.pop()

self._adjust_down(0)

return e0

def build_queue(self): #構建最小堆

j = (len(self._elems)-2)//2

while j>=0:

self._adjust_down(j)

j-=1

def _adjust_down(self,index): #向下調整堆

i,j,length = index,2*index+1,len(self._elems)-1

while j<=length:

if j+1<=length and self._elems[j]>self._elems[j+1]:

j+=1

if self._elems[i] <= self._elems[j]:

break

else:

temp = self._elems[i]

self._elems[i]=self._elems[j]

self._elems[j] = temp

i=2*i+1

j = 2*i+1

def _adjust_up(self,index,e): #向上調整堆

i,j = index,(index-1)//2

while i>0 and eself._elems[i]=self._elems[j]

i,j=j,(i-1)//2

self._elems[i]=e

if __name__=='__main__': #測試用例

queue = prio_queue([6,2,8,3,5,1,7,4])

print(queue.get_head())

print(queue.queue_length())

print(queue.is_empty())

queue.enqueue(4)

queue.enqueue(17)

queue.enqueue(-1)

print(queue.dequeue())

print(queue.dequeue())

queue.clear_queue()

print(queue.queue_length())

print(queue.is_empty())

print(queue.get_head())

用 python 的 list 實現棧

介紹一下 棧作為一種資料結構,是一種只能在一端進行插入和刪除操作的特殊線性表。用 python 的順序表 list 實現 coding utf 8 date 21 50 author sixkery class stact object 棧 構造乙個棧的容器 def init self self.l...

Python實訓(3) 物件導向

來學python物件導向的特性 一天講了太多東西,真就填鴨。class student object 這裡括號內就表示繼承基類,所有類都繼承為object這個 超級類 class student object def init self,name self.name name 用以上 定義類函式,函...

java8 多個list物件用lambda求差集

業務場景 呼叫同步介面獲取當前全部有效賬戶,資料庫已存在部分賬戶資訊,因此需要篩選同步介面中已存在本地的帳戶。呼叫介面獲取的資料集合 listlist response.getdata getitems 本地查詢出來的賬戶集合 listtowlist accountrepository.findal...