hfutils.utils.heap

A generic heap implementation that supports custom comparison keys and reverse ordering.

The implementation uses Python’s built-in heapq module internally while providing a more convenient and feature-rich interface.

Heap

class hfutils.utils.heap.Heap(items: Iterable[T] | None = None, *, key: Callable[[T], Any] | None = None, reverse: bool = False)[source]

A generic heap implementation supporting custom key functions and reverse ordering.

This heap can be used as either a min-heap or max-heap and supports custom key functions for comparison. It provides standard heap operations like push, pop, and peek.

Parameters:
  • items (Optional[Iterable[T]]) – Optional initial items to populate the heap

  • key (Optional[Callable[[T], Any]]) – Optional function to extract comparison keys from items

  • reverse (bool) – Whether to use max-heap instead of min-heap ordering

Example::
>>> # Create a min-heap of numbers
>>> heap = Heap([3, 1, 4, 1, 5])
>>> # Create a max-heap of strings based on length
>>> heap = Heap(['a', 'bbb', 'cc'], key=len, reverse=True)
__bool__()[source]

Boolean representation of the heap.

Returns:

True if the heap is not empty, False otherwise

Return type:

bool

__init__(items: Iterable[T] | None = None, *, key: Callable[[T], Any] | None = None, reverse: bool = False)[source]
__len__() int[source]

Get the number of items in the heap.

Returns:

Number of items in the heap

Return type:

int

__repr__()[source]

Get a string representation of the heap.

Returns:

String representation showing the heap’s items

Return type:

str

property is_empty: bool

Check if the heap is empty.

Returns:

True if the heap has no items, False otherwise

Return type:

bool

pop() T[source]

Remove and return the top item from the heap.

Returns:

The top item from the heap

Return type:

T

Raises:

IndexError – If the heap is empty

push(item: T) None[source]

Push an item onto the heap.

Parameters:

item (T) – Item to add to the heap