Blame
|
1 | # Heapq |
||||||
| 2 | Python’s heapq module implements a min-heap using a regular list. The smallest element is always stored at index 0. |
|||||||
| 3 | ||||||||
| 4 | :::info |
|||||||
| 5 | My usecase was to have a performant collection with a maximum size that removes the worst results to focus on the best. |
|||||||
| 6 | ::: |
|||||||
| 7 | ||||||||
| 8 | ```python= |
|||||||
| 9 | import heapq |
|||||||
| 10 | ||||||||
| 11 | class element: |
|||||||
| 12 | score: int |
|||||||
| 13 | ||||||||
| 14 | def __lt__(self, other): |
|||||||
| 15 | if not isinstance(other, element): |
|||||||
| 16 | return NotImplemented |
|||||||
| 17 | ||||||||
| 18 | return self.score < other.score |
|||||||
| 19 | ||||||||
| 20 | def do_something(): |
|||||||
| 21 | list: list[element] = [] |
|||||||
| 22 | ||||||||
| 23 | ... |
|||||||
| 24 | ||||||||
| 25 | heapq.heappush(list, new_element) |
|||||||
| 26 | ||||||||
| 27 | heapq.heappushpop(list, new_element) |
|||||||
| 28 | ``` |
|||||||
| 29 | - 17: `heappush(heap, item)` inserts a new item while preserving the heap property. |
|||||||
| 30 | - 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. |
|||||||
| 31 | ||||||||
| 32 | :::warning |
|||||||
| 33 | 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. |
|||||||
| 34 | ::: |
|||||||
