########################################
# The contents of this file are subject to the MLX PUBLIC LICENSE version
# 1.0 (the "License"); you may not use this file except in
# compliance with the License.
# 
# Software distributed under the License is distributed on an "AS IS"
# basis, WITHOUT WARRANTY OF ANY KIND, either express or implied.  See
# the License for the specific language governing rights and limitations
# under the License.
# 
# The Original Source Code is "compClust", released 2003 September 03.
# 
# The Original Source Code was developed by the California Institute of
# Technology (Caltech).  Portions created by Caltech are Copyright (C)
# 2002-2003 California Institute of Technology. All Rights Reserved.
########################################
#
# A quick and dirty priority queue from the Python Cookbook
# 
# http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/68435
#
# Changes:
#   Added a peek method

import bisect

class PriorityQueue:
  def __init__(self):
    self.queue = [] 

  def append(self, data, priority):
    """
    append a new element to the queue according to its priority
    """

    bisect.insort(self.queue, (priority, data))

  def pop(self, n):
    """
    pop the highest element of the queue. The n argument is
    here to follow the standard queue protocol
    """  

    return self.queue.pop(0)[1]

  def peek(self, n):
    """
    return the highest element of the queue without removing it. The n
    argument is here to follow the standard queue protocol
    """  
    
    return self.queue[0][1]

  def __len__(self):
    return len(self.queue)
