Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save normanlmfung/1cb1f053a30c4fd7aadf2570e9101f99 to your computer and use it in GitHub Desktop.
Save normanlmfung/1cb1f053a30c4fd7aadf2570e9101f99 to your computer and use it in GitHub Desktop.
python_syntax_heapq
# This is taken DIRECTLY from Geekforgeeks https://www.geeksforgeeks.org/heap-queue-or-heapq-in-python/
import heapq
li = [5, 7, 9, 1, 3]
# If you call heapify, when you call heappop, order 1,3,5,7,8. If you comment out heapify call, heappop oder 5,7,9,1,3
heapq.heapify(li)
while li:
print(heapq.heappop(li))
# Example 2 with tuples: (w, n) where w = weight, n = node id. Heapify uses 'w' to sort first, then 'n' as tie-breaker if there are two/more elements with same 'w'.
li = [ (5,3), (4,2), (3,1), (3,4), (2,5) ]
heapq.heapify(li)
while li:
print(heapq.heappop(li))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment