
from heapq import heappush, heappop

class Heap:
	"""A sorted queue object--pop() retrieves the smallest item in the queue.

	In addition to .push() and .pop(), this supports iteration, so
	for instance you can say:

		h = Heap(...)
		for i in h:		# Equivalent to while(i=h.pop())
			...
			h.push(...)

	And the iteration will continue until and if the heap falls empty.
	"""

	def __init__(self):
		self.heap = []

	def push(self, v):
		"Adds a new item to the heap..."
		heappush(self.heap, v)

	def pop(self):
		"Pops top item and returns it"
		return heappop(self.heap)

	def top(self):
		"Returns top item without popping it"
		return self.heap[0]

	def __len__(self):
		"Number of items left in the heap"
		return len(self.heap)

	def __iter__(self):
		return self

	def next(self):
		if self.heap:
			return heappop(self.heap)
		raise StopIteration

def new():
	return Heap()

