Skip to content

Instantly share code, notes, and snippets.

@terror
Created June 27, 2020 22:46
Show Gist options
  • Save terror/d435119d1eb1b8c7a985aeab6be5162e to your computer and use it in GitHub Desktop.
Save terror/d435119d1eb1b8c7a985aeab6be5162e to your computer and use it in GitHub Desktop.
Priority queue in python standard lib
import heapq
items = [1,2,3,4,5]
pq = []
# Push element onto the heap (adding)
# Note that heapq is min heap by default so smallest element gets max priority
for i in items:
heapq.heappush(pq,i)
# pop element from heap (polling)
item = heappop(pq)
# push element and pop element from the heap at the same time
item = heapq.heappushpop(pq, 5)
# Transform list into a min heap in O(n) time aka Construction
lst = [3,5,6,2,9,1]
heapq.heapify(lst)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment