Skip to content

Instantly share code, notes, and snippets.

@tantalor tantalor/merge.py
Created May 5, 2014

Embed
What would you like to do?
Merge Algorithm
def merge(streams):
# Keep track of the least value in each stream.
head = [stream.next() for stream in streams]
while len(head):
# Yield the least value of all streams.
next = min(head)
yield next
index = head.index(next)
try:
# Get next value from that stream.
head[index] = streams[index].next()
except StopIteration:
# Remove that stream if it is empty.
head.pop(index)
streams.pop(index)
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__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.