Simple cartesian product

Magnus L. Hetland mlh at vier.idi.ntnu.no
Tue Jan 4 18:14:34 EST 2000


mlh at vier.idi.ntnu.no (Magnus L. Hetland) writes:

> mlh at vier.idi.ntnu.no (Magnus L. Hetland) writes:
> 
> > def product(a,b):
> >     a = reduce(lambda l, x: l + [x]*len(b),
> >                [[]] + a)
> >     b = b * len(a)
> >     return map(None, a, b)
> > 
> 
> Or, rather:
> 
> def product(a,b):
>     a2 = reduce(lambda l, x: l + [x]*len(b),
>                [[]] + a)
>     b  = b * len(a)
>     return map(None, a2, b)
> 
> (This is getting worse by the minute ;)

Sorry everybody... (I guess I should have gone to bed by now... ;)

Here is a tested version (not much better, but at least it works)


>>> def product(a,b):
...     a2 = reduce(lambda l, x, n=len(b): l + [x]*n,
...                [[]] + a)
...     b = b * len(a)
...     return map(None, a2, b)
... 
>>> product([1,2,3],[4,5,6])
[(1, 4), (1, 5), (1, 6), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6)]
>>> 


--

  Magnus
  Lie
  Hetland



More information about the Python-list mailing list