Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Apr 29th, 2012  |  syntax: None  |  size: 1.51 KB  |  hits: 11  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. How to put items into priority queues?
  2. PriorityQueue.put(item, priority)
  3.        
  4. from Queue import PriorityQueue
  5.  
  6. class MyPriorityQueue(PriorityQueue):
  7.     def __init__(self):
  8.         PriorityQueue.__init__(self)
  9.         self.counter = 0
  10.  
  11.     def put(self, item, priority):
  12.         PriorityQueue.put(self, (priority, self.counter, item))
  13.         self.counter += 1
  14.  
  15.     def get(self, *args, **kwargs):
  16.         _, _, item = PriorityQueue.get(self, *args, **kwargs)
  17.         return item
  18.  
  19.  
  20. queue = MyPriorityQueue()
  21. queue.put('item2', 1)
  22. queue.put('item1', 1)
  23.  
  24. print queue.get()
  25. print queue.get()
  26.        
  27. item2
  28. item1
  29.        
  30. import Queue as queue
  31.  
  32. prio_queue = queue.PriorityQueue()
  33. prio_queue.put((2, 8, 'super blah'))
  34. prio_queue.put((1, 4, 'Some thing'))
  35. prio_queue.put((1, 3, 'This thing would come after Some Thing if we sorted by this text entry'))
  36. prio_queue.put((5, 1, 'blah'))
  37.  
  38. while not prio_queue.empty():
  39.     item = prio_queue.get()
  40.     print('%s.%s - %s' % item)
  41.        
  42. 1.3 - This thing would come after Some Thing if we didn't add a secondary priority
  43. 1.4 - Some thing
  44. 2.8 - super blah
  45. 5.1 - blah
  46.        
  47. import Queue as queue
  48. import time
  49.  
  50. prio_queue = queue.PriorityQueue()
  51. prio_queue.put((2, time.time(), 'super blah'))
  52. time.sleep(0.1)
  53. prio_queue.put((1, time.time(), 'This thing would come after Some Thing if we sorted by this text entry'))
  54. time.sleep(0.1)
  55. prio_queue.put((1, time.time(), 'Some thing'))
  56. time.sleep(0.1)
  57. prio_queue.put((5, time.time(), 'blah'))
  58.  
  59. while not prio_queue.empty():
  60.     item = prio_queue.get()
  61.     print('%s.%s - %s' % item)