Package elisa :: Package extern :: Module priority_queue
[hide private]
[frames] | no frames]

Source Code for Module elisa.extern.priority_queue

 1  # -*- coding: utf-8 -*- 
 2  # from http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/87369 
 3  # Licensed under PSF: http://python.org/license 
 4   
 5  import Queue 
 6  import bisect 
 7  import sys 
 8   
 9   
10 -class PriorityQueue(Queue.Queue):
11
12 - def _init(self, maxsize):
13 self.maxsize = maxsize 14 self.queue = []
15
16 - def _put(self, item):
17 data, priority = item 18 self._insort_right((priority, data))
19
20 - def _get(self):
21 return self.queue.pop(0)[1]
22
23 - def _insort_right(self, x):
24 """Insert item x in list, and keep it sorted assuming a is sorted. 25 26 If x is already in list, insert it to the right of the rightmost x. 27 """ 28 a = self.queue 29 lo = 0 30 hi = len(a) 31 32 while lo < hi: 33 mid = (lo+hi)/2 34 if x[0] < a[mid][0]: 35 hi = mid 36 else: 37 lo = mid+1 38 a.insert(lo, x)
39
40 - def top(self):
41 "non-destructively return smallest element in pqueue" 42 try: 43 x = self.queue[0] 44 except IndexError: 45 x = None 46 return x
47
48 - def contents(self):
49 return self.queue
50
51 -def test():
52 pq = PriorityQueue() 53 54 pq.put(('b', 1)) 55 pq.put(('a', 1)) 56 pq.put(('c', 1)) 57 pq.put(('z', 0)) 58 pq.put(('d', 2)) 59 60 while not pq.empty(): 61 print pq.get(),
62 63 if __name__ == '__main__': 64 test() # prints z b a c d 65