Skip to content

Instantly share code, notes, and snippets.

@nasturtus
Created May 11, 2017 03:59
Show Gist options
  • Save nasturtus/2ad416dee9bebf2f88f2d912450dde32 to your computer and use it in GitHub Desktop.
Save nasturtus/2ad416dee9bebf2f88f2d912450dde32 to your computer and use it in GitHub Desktop.
# Priority Queues
# From: https://dbader.org/blog/priority-queues-in-python
# Sorted list
sl = []
sl.append((3, 'Sleep'))
sl.append((1, 'Eat'))
sl.append((2, 'Code'))
sl.sort(reverse=True)
while sl:
next_item = sl.pop()
print(next_item)
print()
# heapq
import heapq
hq = []
heapq.heappush(hq, (3, 'Sleep'))
heapq.heappush(hq, (1, 'Eat'))
heapq.heappush(hq, (2, 'Code'))
while hq:
next_item = heapq.heappop(hq)
print(next_item)
print()
# PriorityQueue
from queue import PriorityQueue
pq = PriorityQueue()
pq.put((3, 'Sleep'))
pq.put((1, 'Eat'))
pq.put((2, 'Code'))
while not pq.empty():
next_item = pq.get()
print(next_item)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment