Created
June 27, 2020 22:46
-
-
Save terror/d435119d1eb1b8c7a985aeab6be5162e to your computer and use it in GitHub Desktop.
Priority queue in python standard lib
This file contains 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
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