classminheap(object):"""implements a minheap"""def__init__(self,cap=100):"""creates an empty minheap with the given capacity"""self.__h=[Noneforiinrange(cap)]self.__len=0def__str__(self):"""return the string representation of the minheap"""returnstr(self.__h[:self.__len])def__len__(self):"""return the number of elements in the collection"""returnself.__lendefcapacity(self):"""return the capacity of the minheap"""returnlen(self.__h)defis_empty(self):"""return if the collection is empty or not"""returnlen(self)==0defis_full(self):"""return if the collection is full or not"""returnlen(self)==len(self.__h)def__parent(self,i):"""return the index of the parent of the given index"""return(i-1)>>1def__left(self,i):"""return the index of the left child of the given index"""return1+(i<<1)def__right(self,i):"""return the index of the right child of the given index"""return(i+1)<<1def__heapify_up(self,i):"""moves the element up in the tree assuming that the rest of the tree satisfies the heap property """ifi>0:p=self.__parent(i)ifself.__h[p]>self.__h[i]:self.__h[p],self.__h[i]=self.__h[i],self.__h[p]self.__heapify_up(p)def__heapify_down(self,i):"""moves the element down in the tree assuming that the rest of the tree satisfies the heap property """l,r,b=self.__left(i),self.__right(i),iifl<len(self)andself.__h[l]<self.__h[b]:b=lifr<len(self)andself.__h[r]<self.__h[b]:b=rifb!=i:self.__h[b],self.__h[i]=self.__h[i],self.__h[b]self.__heapify_down(b)defget_min(self):"""return the minimum of the collection"""assertlen(self)!=0returnself.__h[0]defremove_min(self):"""remove the minimum of the collection"""assertlen(self)!=0self.__h[0]=self.__h[len(self)-1];self.__len-=1iflen(self)>1:self.__heapify_down(0)definsert(self,x):"""insert the element in the collection"""assertlen(self)!=self.capacity()self.__h[len(self)]=x;self.__len+=1ifself.__len>1:self.__heapify_up(self.__len-1)
Comments (0)
HTTPSSSH
You can clone a snippet to your computer for local editing.
Learn more.