fork download
  1. #!/usr/bin/env python
  2. # from http://stackoverflow.com/a/19475021/
  3. import heapq
  4.  
  5. def addtoheap(h, it):
  6. try:
  7. heapq.heappush(h, (next(it), it))
  8. except StopIteration:
  9. pass
  10.  
  11. def mergek(*lists):
  12. h = []
  13. for it in map(iter, lists):
  14. addtoheap(h, it)
  15. while h:
  16. min_, it = heapq.heappop(h)
  17. addtoheap(h, it)
  18. yield min_
  19.  
  20. for x in mergek([1, 3, 5], [2, 4, 6], [7, 8, 9], [10]):
  21. print(x)
  22.  
Success #stdin #stdout 0.01s 9992KB
stdin
Standard input is empty
stdout
1
2
3
4
5
6
7
8
9
10