danilobellini

Priority Queue in Python standard library

Sep 25th, 2014
310
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.03 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # Created on Thu Sep 25 20:17:57 2014
  4. # @author: Danilo de Jesus da Silva Bellini
  5. """
  6. Priority Queue in Python standard library.
  7.  
  8. Using Queue/queue module, or heapq module directly.
  9. """
  10. from __future__ import print_function
  11.  
  12. from heapq import heappush, heappop
  13. try:
  14.   from Queue import PriorityQueue # Python 2
  15. except ImportError:
  16.   from queue import PriorityQueue # Python 3
  17.  
  18.  
  19. print("Using the {} module!".format(PriorityQueue.__module__))
  20.  
  21.  
  22. q = PriorityQueue()
  23. for el in [5, 2, 7, 9, 3, 1]:
  24.   q.put(el)
  25.  
  26. print(q.get())
  27. print(q.get())
  28. q.put(4)
  29. print(q.get())
  30. q.put(14)
  31. q.put(2)
  32. print(q.get())
  33. print(q.get())
  34. q.put(13)
  35. while not q.empty():
  36.   print(q.get())
  37.  
  38. print()
  39.  
  40.  
  41. print("Using the heapq module!")
  42.  
  43. pq = []
  44.  
  45. for el in [5, 2, 7, 9, 3, 1]:
  46.   heappush(pq, el)
  47.  
  48. print(heappop(pq))
  49. print(heappop(pq))
  50. heappush(pq, 4)
  51. print(heappop(pq))
  52. heappush(pq, 14)
  53. heappush(pq, 2)
  54. print(heappop(pq))
  55. print(heappop(pq))
  56. heappush(pq, 13)
  57. while pq:
  58.   print(heappop(pq))
Advertisement
Add Comment
Please, Sign In to add comment