1 #!/usr/bin/env python 2 3 class QueueUnderflow(ValueError): 4 pass 5 6 class PrioQue(object): 7 def __init__(self, elems=[]): 8 #list can be change locally, so list it 9 self.elems = list(elems) 10 self.elems.sort(reverse=True) 11 12 def is_empty(self): 13 return self.elems == None 14 15 def peek(self): 16 if self.is_empty(): 17 raise QueueUnderflow 18 return self.elems[-1] 19 20 def dequeue(self): 21 if self.is_empty(): 22 raise QueueUnderflow 23 return self.elems.pop() 24 25 def enqueue(self, elem): 26 i = len(self.elems) - 1 27 while i>=0: 28 if self.elems[i] <= elem: 29 i -= 1 30 else: 31 break 32 self.elems.insert(i+1, elem) 33 34 if __name__ == '__main__': 35 pq = PrioQue(elems=[6,4,3,8,5,1,2,0,9]) 36 print(pq.elems) 37 pq.enqueue(7) 38 print(pq.elems)