Skip to content

Instantly share code, notes, and snippets.

Created May 5, 2014
What would you like to do?
Merge Algorithm
def merge(streams):
# Keep track of the least value in each stream.
head = [ for stream in streams]
while len(head):
# Yield the least value of all streams.
next = min(head)
yield next
index = head.index(next)
# Get next value from that stream.
head[index] = streams[index].next()
except StopIteration:
# Remove that stream if it is empty.
def main():
stream1 = iter([10, 20, 30])
stream2 = iter([11, 21, 31, 41, 51])
stream3 = merge([stream1, stream2])
for i in stream3:
print i
if __name__ == '__main__':
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment