```
# python 2 or 3
"""
Author: Written by Gribouillis for the python forum at www.daniweb.com
Date: November 15, 2010
License: public domain
"""
def merged(*iterables):
"""Merge a sequence of sorted iterables into a single iterable.
contract:
* each iterable argument is sorted in ascending order.
* the returned iterable is sorted in ascending order
"""
import sys
if sys.version_info < (3,):
import Queue as queue
else:
import queue
iterables = [iter(it) for it in iterables]
heap = queue.PriorityQueue(len(iterables))
for n, it in enumerate(iterables):
try:
heap.put((next(it), n), block = False)
except StopIteration:
pass
try:
while True:
item, n = heap.get(block = False)
heap.task_done()
yield item
try:
heap.put((next(iterables[n]), n))
except StopIteration:
pass
except queue.Empty:
raise StopIteration
if __name__ == "__main__":
from random import random
from pprint import pprint
L = [ sorted(random() for i in range(n)) for n in (10, 5, 15) ]
pprint(L)
pprint(list(merged(*L)))
```

**Are you able to help answer this sponsored question?**

Questions asked by members who have earned a lot of community kudos are featured in order to give back and encourage quality replies.

Recommended Topics