Simple cartesian product

Neel Krishnaswami neelk at brick.cswv.com
Wed Jan 5 19:38:17 EST 2000


Neel Krishnaswami <neelk at brick.cswv.com> wrote:
> 
> Here's my entry:
> 
> def product(a, b):
>     u = map(lambda i: a[i/len(a)], range(len(a)*len(b)))
>     v = map(lambda j: b[j%len(b)], range(len(a)*len(b))) # Same as b*len(a)
>     return map(None, u, v)

I realized this can be condensed even further:

def product(a, b):
    return map(lambda n,a=a,b=b: (a[n/len(b)], b[n%len(b)]),
               range(len(a)*len(b)))

It's still slower and more memory-hungry than the obvious for-loop,
though.


Neel






More information about the Python-list mailing list