Commit f73c61
2026-08-06 23:44:54 Niklas Polke: Create Heapq| /dev/null .. python/heapq.md | |
| @@ 0,0 1,34 @@ | |
| + | # Heapq |
| + | Python’s heapq module implements a min-heap using a regular list. The smallest element is always stored at index 0. |
| + | |
| + | :::info |
| + | My usecase was to have a performant collection with a maximum size that removes the worst results to focus on the best. |
| + | ::: |
| + | |
| + | ```python= |
| + | import heapq |
| + | |
| + | class element: |
| + | score: int |
| + | |
| + | def __lt__(self, other): |
| + | if not isinstance(other, element): |
| + | return NotImplemented |
| + | |
| + | return self.score < other.score |
| + | |
| + | def do_something(): |
| + | list: list[element] = [] |
| + | |
| + | ... |
| + | |
| + | heapq.heappush(list, new_element) |
| + | |
| + | heapq.heappushpop(list, new_element) |
| + | ``` |
| + | - 17: `heappush(heap, item)` inserts a new item while preserving the heap property. |
| + | - 19: `heappushpop(heap, item)` first inserts the item and then removes and returns the smallest element. It is usually more efficient than calling heappush() followed by heappop() separately. |
| + | |
| + | :::warning |
| + | Heap elements must be mutually comparable. For custom classes, implementing __lt__() is normally sufficient, because heapq compares elements using the < operator. If two elements cannot be compared, Python raises a TypeError. A common alternative is to store tuples such as (priority, value), where the first element defines the priority. |
| + | ::: |
