Iterating over several lists at once

John Henry john106henry at hotmail.com
Thu Dec 14 15:07:02 EST 2006


Is this suppose to be a brain teaser or something?

Michael Spencer wrote:
> John Henry wrote:
> > Carl Banks wrote:
> > <snip>
> >> The function can be extended to allow arbitrary arguments.  Here's a
> >> non-minmal recursive version.
> >>
> >> def cartesian_product(*args):
> >>     if len(args) > 1:
> >>         for item in args[0]:
> >>             for rest in cartesian_product(*args[1:]):
> >>                 yield (item,) + rest
> >>     elif len(args) == 1:
> >>         for item in args[0]:
> >>             yield (item,)
> >>     else:
> >>         yield ()
> >>
> >>
> >
> > Very nice.
> >
> another implementation of cartesian_product using 'reduce' to add
> mystery ;-)
>
> def star(outer, inner):
>      for rest in outer:
>          for item in inner:
>              yield rest + (item,)
>
> def cartesian_product(*args):
>      return reduce(star, args, ((),))
>
>   >>> list(cartesian_product("01","01","01"))
>   [('0', '0', '0'), ('0', '0', '1'), ('0', '1', '0'), ('0', '1', '1'),
> ('1', '0', '0'), ('1', '0', '1'), ('1', '1', '0'), ('1', '1', '1')]
>   >>>
> 
> Michael




More information about the Python-list mailing list