This snippet defines a function to merge sorted iterables containing similar items into a single iterable. Items are supposed to be sorted in ascending order. Only one item per iterable is stored at a time.
Merge Sorted Iterables
# 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)))
TrustyTony 888 ex-Moderator Team Colleague Featured Poster
arkoenig 340 Practically a Master Poster
TrustyTony 888 ex-Moderator Team Colleague Featured Poster
Gribouillis 1,391 Programming Explorer Team Colleague
Gribouillis 1,391 Programming Explorer Team Colleague
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.