I only need to retrieve the 3 smallest elements, and wondering if there is a way to improve my below code to keep heap size smaller -- I think if we only need to keep heap size as 3, it is enough. But cannot find an option in heapq to tweak.
In other words, I want to want to maintain a three element heap that is occasionally updated.
import heapq
def heapsort(iterable):
h = []
for value in iterable:
heapq.heappush(h, value)
return [heapq.heappop(h) for i in range(len(h))]
if __name__ == "__main__":
print heapsort([1, 3, 5, 7, 9, 2, 4, 6, 8, 0])