[Python-ideas] Function to unnest for-statements

Brandon Mintern bmintern at gmail.com
Fri May 23 10:51:05 CEST 2008


On Fri, May 23, 2008 at 4:38 AM, Brandon Mintern <bmintern at gmail.com> wrote:
> def combinations (*args):
>   def combiner (seqs):
>       try:
>           seq0 = seqs.next()
>       except StopIteration:
>           yield ()
>       else:
>           for prefix in combiner(iter(seqs)):
>               for x in seq0:
>                   yield prefix + (x,)
>   return combiner(reversed(args))

I was incorrectly thinking that combiner would be called more than
once on seqs, and thus I used iter(seqs) to avoid making a call on an
exhausted iterator. It turns out that's unnecessary since there is
only one recursive call per call to combiner, so the result is the
somewhat improved:

def combinations (*args):
    def combiner (seqs):
        try:
            seq0 = seqs.next()
        except StopIteration:
            yield ()
        else:
            for prefix in combiner(seqs):
                for x in seq0:
                    yield prefix + (x,)
    return combiner(reversed(args))

I think this is a solution I can be proud of, in terms of correctness
(iterating in the proper order), readability, and efficiency.

Brandon



More information about the Python-ideas mailing list