iterator? way of generating all possible combinations?
Scott David Daniels
scott.daniels at acm.org
Wed May 31 12:45:10 EDT 2006
Jim Segrave wrote:
> In article <447cadf6$1 at nntp0.pdx.net>,
> Scott David Daniels <scott.daniels at acm.org> wrote:
>> class FileReIterable2(object):
>> ...
>> def __iter__(self):
>> self.file.seek(0)
>> for line in self.file:
>> nextpos = self.file.tell()
>> yield line
>> self.file.seek(nextpos)
>
> Hmm - I tried this with 'one.file' being ... letters, one per line:
>
> gen = FileReIterable2("one.file")
> for a in gen:
> for b in gen:
> print a.strip(), b.strip()
>
> which didn't produce lines 'a a', 'a b', etc. It produced the single
> line 'a a', then stopped....
Oops. This works in Python 2.5 (and later) because the file.tell and
file.seek code are aware of the file iteration buffering. Since I am
trying to test all of my stuff on 2.5, that is what I am using by
default.
> Rewriting the __iter__ method to not internally iterate over the file
> object, as follows, works ....
>
> class FileReIterable2(object):
> ...
> def __iter__(self):
> self.file.seek(0)
> while True:
> line = self.file.readline()
> if line == '': raise StopIteration
> nextpos = self.file.tell()
> yield line
> self.file.seek(nextpos)
This fix does in fact provide working behavior for Pythons before 2.5.
--Scott David Daniels
scott.daniels at acm.org
More information about the Python-list
mailing list