Created
March 9, 2026 22:58
-
-
Save mshafae/e8f2c047f5e43550b919ac2b5fc3dc5e to your computer and use it in GitHub Desktop.
CPSC 386 example of how to use the Python heapq library
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python3 | |
| # Gist: https://gist.github.com/mshafae/e8f2c047f5e43550b919ac2b5fc3dc5e | |
| # | |
| "Examples of how to work with Python's heap library" | |
| from collections import namedtuple | |
| from random import randint | |
| import heapq | |
| import pprint | |
| import sys | |
| def main(): | |
| if sys.version_info > (3, 13): | |
| print('The heapq library now has heapq.heapify_max()') | |
| print('See https://docs.python.org/3/library/heapq.html') | |
| TTTMove = namedtuple('TTTMove', ['priority', 'junk']) | |
| # The priority is set to a negative number so we get max_heap behavior | |
| # from Python's min_heap. Ubuntu 24 uses Python 3.12 so we can't use | |
| # the new heapify_max(). | |
| move_list = [TTTMove((randint(1, 100)) * -1, 'foo') for _ in range(5)] | |
| print('Initial state of the list') | |
| pprint.pprint(move_list) | |
| # Heapify the list; remember heaps are actually trees | |
| heapq.heapify(move_list) | |
| print("Heapified:") | |
| pprint.pprint(move_list) | |
| n = heapq.heappop(move_list) | |
| print('Popped') | |
| pprint.pprint(n) | |
| print('List state') | |
| pprint.pprint(move_list) | |
| print('Push') | |
| heapq.heappush(move_list, TTTMove((randint(1, 1000)) * -1, 'foo')) | |
| print('List state') | |
| pprint.pprint(move_list) | |
| n = heapq.heappop(move_list) | |
| print('Popped') | |
| pprint.pprint(n) | |
| print('List state') | |
| pprint.pprint(move_list) | |
| print('Push') | |
| heapq.heappush(move_list, TTTMove((randint(1, 100)) * -1, 'foo')) | |
| print('List state') | |
| pprint.pprint(move_list) | |
| n = heapq.heappop(move_list) | |
| print('Popped') | |
| pprint.pprint(n) | |
| if __name__ == '__main__': | |
| main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment