generating points on a grid - efficiently

Thomas Heller theller at python.net
Mon Mar 8 10:46:30 CET 2004


Rajarshi Guha <rajarshi at presidency.com> writes:

> Hi, 
>  I've written some code that takes a N lists of numbers (corresponding to
> axes) and generates a list of grid points (N dimensional grid) for the
> supplied axes. So as an example say my two axes are defined as
>
> v1 = [1,2,3]
> v2 = [1,2,3]
>
> My code will return to me a list of points: 
>
> (1,1), (1,2), (1,3) ....(3,1), (3,2), (3,3)
>
> and so on. For 3 axes, I would obtain 27 points and so on.
> I've included the code below.
[...]
> It seems that this could be formulated as a recursive problem but I
> can't seem to get at it.

Here is a recursive solution using generators:

from __future__ import generators

def _gen_grid(v):
    rest = v[1:]
    if rest:
        for a in v[0]:
            for b in gen_grid(rest):
                yield [a] + b
    else:
        for a in v[0]:
            yield [a]

def gen_grid(v):
    return [x for x in _gen_grid(v)]



v1 = [1, 2]
v2 = [3, 4]
v3 = [5, 6]

print gen_grid((v1, v2, v3))

Thomas





More information about the Python-list mailing list