Simple cartesian product

Tim Hochberg tim.hochberg at ieee.org
Tue Jan 4 20:01:39 EST 2000


"Magnus L. Hetland" mailto:mlh at vier.idi.ntnu.no wants a Cartesian product:

If you can use Numeric and you're limiting yourself to numbers, there are
several ways to do it, one of which is shown below. It's not as short as
yours, but I almost guarentee its faster. Figuring out why this code is the
way it is is left as an excercise for the reader.

def product(a, b):
    a = asarray(a, 'O')
    b = asarray(b, 'O')
    result = zeros((len(a), len(b), 2),  'O')
    result[:,:,0] = result[:,:,0]  + a[:,NewAxis]
    result[:,:,1] =  result[:,:,1]  + b[NewAxis,:]
    result.shape = len(a) * len(b), 2
    return result.tolist()

If you need to use objects other than numbers, I believe the following
should work. (It may get confused if you feed the elements of the original
lists are sequences). This code is weird because of the rules as to when
Numeric makes copies of arrays. Figuring it out is another excercise
<0.5wink>.

def product2(a, b):
    result = zeros((len(a), len(b), 2),  'O')
    reshape(result , (-1,2))[:,0] = a*len(b)
    result = array(transpose(result, (1,0,2)))
    reshape(result , (-1, 2))[:,1] =  b*len(a)
    result = reshape(transpose(result, (1,0,2)), (-1, 2))
    return result.tolist()


-tim





More information about the Python-list mailing list