Each function is its heapq namesake with the prefix max, same signature, and
the largest item comes out first. Items can be anything with <, tuples
included: there is no negation and no wrapper, so h[0] is the largest item
and iterating h gives the items.
A heap class and draw_heap, which draws a list heap as the tree it is.
A heap of items, smallest first, or largest first with type=max.
push, pop and peek as the words say; append is push, so a heap can
stand in for a list. len and iteration work; iteration is heap order,
not sorted order. h is the list of items in heap order, for min and
max the same.
Source code in pydsa/heaps.mu
6465666768697071727374757677787980818283
classheap"""A heap of items, smallest first, or largest first with type=max. push, pop and peek as the words say; append is push, so a heap can stand in for a list. len and iteration work; iteration is heap order, not sorted order. h is the list of items in heap order, for min and max the same."""def__init__(items=(),type=min)self.before=typeismax?_gt:_ltself.h=listitemsforiinreversed(0..<len(self.h)//2)_down(self.h,i,self.before)defpush(x)->none:_push(self.h,x,self.before)defpop():_pop(self.h,self.before)defpeek():self.h[0]def__len__():lenself.hdef__iter__():iterself.happend=push
classheap:"""A heap of items, smallest first, or largest first with type=max. push, pop and peek as the words say; append is push, so a heap can stand in for a list. len and iteration work; iteration is heap order, not sorted order. h is the list of items in heap order, for min and max the same."""def__init__(self,items=(),type=min):self.before=_gtiftypeismaxelse_ltself.h=list(items)foriinreversed(range(0,len(self.h)//2)):_down(self.h,i,self.before)defpush(self,x)->None:_push(self.h,x,self.before)defpop(self):return_pop(self.h,self.before)defpeek(self):returnself.h[0]def__len__(self):returnlen(self.h)def__iter__(self):returniter(self.h)append=push
Utility function to draw a heap represented as a list in the terminal.
The heap list is assumed to be in level-order (array representation of a complete binary tree).
Source code in pydsa/heaps.mu
858687888990919293
defdraw_heap(heap_list:[int])->none""" Utility function to draw a heap represented as a list in the terminal. The heap list is assumed to be in level-order (array representation of a complete binary tree). """ifnotheap_listprint"Empty heap"returndraw_tree(build_tree(list(heap_list)))
120121122123124125126127128
defdraw_heap(heap_list:list[int])->None:""" Utility function to draw a heap represented as a list in the terminal. The heap list is assumed to be in level-order (array representation of a complete binary tree). """ifnotheap_list:print("Empty heap")returndraw_tree(build_tree(list(heap_list)))