python 二元堆積

來源:互聯網
上載者:User

標籤:列表   一個   二元堆積   span   current   sel   nbsp   添加   tmp   

  • BinaryHeap() 建立一個新的,空的二元堆積。
  • insert(k) 向堆添加一個新項。
  • findMin() 返回具有最小索引值的項,並將項留在堆中。
  • delMin() 返回具有最小索引值的項,從堆中刪除該項。
  • 如果堆是空的,isEmpty() 返回 true,否則返回 false。
  • size() 返回堆中的項數。
  • buildHeap(list) 從鍵列表構建一個新的堆。
from pythonds.trees.binheap import BinHeapbh = BinHeap()bh.insert(5)bh.insert(7)bh.insert(3)bh.insert(11)print(bh.delMin())print(bh.delMin())print(bh.delMin())print(bh.delMin())
class BinHeap:    def __init__(self):        self.heapList = [0]        self.currentSize = 0    def percUp(self,i):        while i // 2 > 0:          if self.heapList[i] < self.heapList[i // 2]:             tmp = self.heapList[i // 2]             self.heapList[i // 2] = self.heapList[i]             self.heapList[i] = tmp          i = i // 2    def insert(self,k):      self.heapList.append(k)      self.currentSize = self.currentSize + 1      self.percUp(self.currentSize)    def percDown(self,i):      while (i * 2) <= self.currentSize:          mc = self.minChild(i)          if self.heapList[i] > self.heapList[mc]:              tmp = self.heapList[i]              self.heapList[i] = self.heapList[mc]              self.heapList[mc] = tmp          i = mc    def minChild(self,i):      if i * 2 + 1 > self.currentSize:          return i * 2      else:          if self.heapList[i*2] < self.heapList[i*2+1]:              return i * 2          else:              return i * 2 + 1    def delMin(self):      retval = self.heapList[1]      self.heapList[1] = self.heapList[self.currentSize]      self.currentSize = self.currentSize - 1      self.heapList.pop()      self.percDown(1)      return retval    def buildHeap(self,alist):      i = len(alist) // 2      self.currentSize = len(alist)      self.heapList = [0] + alist[:]      while (i > 0):          self.percDown(i)          i = i - 1bh = BinHeap()bh.buildHeap([9,5,6,2,3])print(bh.delMin())print(bh.delMin())print(bh.delMin())print(bh.delMin())print(bh.delMin())

 

python 二元堆積

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.