paul@33 | 1 | #!/usr/bin/env python |
paul@33 | 2 | |
paul@48 | 3 | """ |
paul@48 | 4 | An iterator merging class similar to heapq.merge in Python 2.6. |
paul@48 | 5 | |
paul@48 | 6 | Copyright (C) 2009 Paul Boddie <paul@boddie.org.uk> |
paul@48 | 7 | |
paul@48 | 8 | This program is free software; you can redistribute it and/or modify it under |
paul@48 | 9 | the terms of the GNU General Public License as published by the Free Software |
paul@48 | 10 | Foundation; either version 3 of the License, or (at your option) any later |
paul@48 | 11 | version. |
paul@48 | 12 | |
paul@48 | 13 | This program is distributed in the hope that it will be useful, but WITHOUT ANY |
paul@48 | 14 | WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A |
paul@48 | 15 | PARTICULAR PURPOSE. See the GNU General Public License for more details. |
paul@48 | 16 | |
paul@48 | 17 | You should have received a copy of the GNU General Public License along |
paul@48 | 18 | with this program. If not, see <http://www.gnu.org/licenses/>. |
paul@48 | 19 | """ |
paul@33 | 20 | |
paul@34 | 21 | from bisect import insort_right |
paul@33 | 22 | |
paul@34 | 23 | class itermerge: |
paul@33 | 24 | |
paul@34 | 25 | """ |
paul@34 | 26 | Merge ordered sequences to produce an ordered, combined sequence of |
paul@34 | 27 | results. |
paul@34 | 28 | """ |
paul@33 | 29 | |
paul@34 | 30 | def __init__(self, sequences): |
paul@34 | 31 | self.iters = [] |
paul@34 | 32 | |
paul@34 | 33 | # Prepare the underlying iterators. |
paul@34 | 34 | |
paul@34 | 35 | for seq in sequences: |
paul@34 | 36 | it = iter(seq) |
paul@34 | 37 | next = it.next |
paul@34 | 38 | self._add_next(next) |
paul@33 | 39 | |
paul@34 | 40 | def sort(self): |
paul@34 | 41 | pass # The output should be sorted. |
paul@34 | 42 | |
paul@34 | 43 | def __iter__(self): |
paul@34 | 44 | return self |
paul@34 | 45 | |
paul@34 | 46 | def _add_next(self, next): |
paul@33 | 47 | |
paul@34 | 48 | """ |
paul@34 | 49 | Store the current value for an iterator, alongside the means of |
paul@34 | 50 | getting the next value: the 'next' method. |
paul@34 | 51 | """ |
paul@34 | 52 | |
paul@34 | 53 | try: |
paul@34 | 54 | insort_right(self.iters, (next(), next)) |
paul@34 | 55 | except StopIteration: |
paul@34 | 56 | pass |
paul@34 | 57 | |
paul@34 | 58 | def next(self): |
paul@34 | 59 | if self.iters: |
paul@34 | 60 | value, next = self.iters[0] |
paul@34 | 61 | del self.iters[0] |
paul@34 | 62 | self._add_next(next) |
paul@34 | 63 | return value |
paul@33 | 64 | else: |
paul@34 | 65 | raise StopIteration |
paul@33 | 66 | |
paul@33 | 67 | # vim: tabstop=4 expandtab shiftwidth=4 |