Skip to content

Instantly share code, notes, and snippets.

@tantalor
Created May 5, 2014 17:51
Show Gist options
  • Save tantalor/7570bd753a274dd15c71 to your computer and use it in GitHub Desktop.
Save tantalor/7570bd753a274dd15c71 to your computer and use it in GitHub Desktop.
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