git.fiddlerwoaroof.com
scripts/partial_sort
7fa89c89
 #!/usr/bin/python -u
 from __future__ import print_function
 
 import heapq
 
 def file_iter(fil):
b2c7a946
     the_line = 0
     while the_line != '':
288a9468
         next_line = fil.readline().strip()
         if next_line != '':
             # yield int(next_line)
             yield next_line
         the_line = next_line
7fa89c89
 
 def sorter(gen, len_):
b2c7a946
     the_buffer = []
 
     for the_line in gen:
288a9468
         # print("pushing: ", the_line)
b2c7a946
         heapq.heappush(the_buffer, the_line)
         if len(the_buffer) == len_:
288a9468
             # print("buffer_before: ", repr(the_buffer))
b2c7a946
             yield heapq.heappop(the_buffer)
         # print("buffer_after: ", repr(the_buffer))
 
     while the_buffer != []:
         yield heapq.heappop(the_buffer)
         # print("buffer_after: ", repr(the_buffer))
7fa89c89
 
 
 if __name__ == '__main__':
     import sys
288a9468
     for line in sorter(file_iter(sys.stdin), int(sys.argv[1])):
         print(line)