You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

37 lines
1.1 KiB

  1. # Misc iterator tools
  2. # Iterator merging, based on http://code.activestate.com/recipes/491285/
  3. import heapq
  4. def imerge(*iterables):
  5. '''Merge multiple sorted inputs into a single sorted output.
  6. Equivalent to: sorted(itertools.chain(*iterables))
  7. >>> list(imerge([1,3,5,7], [0,2,4,8], [5,10,15,20], [], [25]))
  8. [0, 1, 2, 3, 4, 5, 5, 7, 8, 10, 15, 20, 25]
  9. '''
  10. heappop, siftup, _Stop = heapq.heappop, heapq._siftup, StopIteration
  11. h = []
  12. h_append = h.append
  13. for it in map(iter, iterables):
  14. try:
  15. next = it.__next__
  16. h_append([next(), next])
  17. except _Stop:
  18. pass
  19. heapq.heapify(h)
  20. while 1:
  21. try:
  22. while 1:
  23. v, next = s = h[0] # raises IndexError when h is empty
  24. yield v
  25. s[0] = next() # raises StopIteration when exhausted
  26. siftup(h, 0) # restore heap condition
  27. except _Stop:
  28. heappop(h) # remove empty iterator
  29. except IndexError:
  30. return