nested for loop

Sean Ross sross at connectmail.carleton.ca
Mon May 10 22:10:00 EDT 2004


"Wolfgang Buechel" <wjb131 at web.de> wrote in message
news:4629559b.0405101330.286ddb32 at posting.google.com...
> Hi,
>
> I want to iterate over all 2x2 matrices with elements in range 0..25
> (crypto-stuff).
[snip]
> Is there a shorter (and probably, with respect to exec time, faster)
> way to write such a 4for loop?
> (I want to scan 3x3, 4x4 matrices too (;-)
>
> -- Wolfgang

Hi.

The following code isn't necessarily shorter or faster (or more readable),
but it's a bit more general:

# slightly modified code from
http://twistedmatrix.com/wiki/python/PostYourCode
def sequences(n, things):
    "generates sequences of n items from a set of things"
    if n == 0:
        yield []
    else:
        for x in things:
            for y in sequences(n-1, things):
                yield [x] + y

def nXn_matrices(n, elements):
    "generates nXn matrices from elements"
    for s in sequences(n*n, elements):
        yield [s[i*n:(i+1)*n] for i in xrange(n)]



# we'll try it over a small range ...
M = 3
for m in nXn_matrices(2, range(M)):
    print m

Output:
[[0, 0], [0, 0]]
[[0, 0], [0, 1]]
[[0, 0], [0, 2]]
[[0, 0], [1, 0]]
[[0, 0], [1, 1]]
[[0, 0], [1, 2]]
[[0, 0], [2, 0]]
...
...
[[2, 2], [2, 0]]
[[2, 2], [2, 1]]
[[2, 2], [2, 2]]



# now 3X3 ... this takes a _l_o_n_g_ time ...
M = 3
for m in nXn_matrices(3,range(M)):
    print m

Output:
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
[[0, 0, 0], [0, 0, 0], [0, 0, 1]]
[[0, 0, 0], [0, 0, 0], [0, 0, 2]]
[[0, 0, 0], [0, 0, 0], [0, 1, 0]]
[[0, 0, 0], [0, 0, 0], [0, 1, 1]]
[[0, 0, 0], [0, 0, 0], [0, 1, 2]]
...
...
[[2, 2, 2], [2, 2, 2], [2, 1, 0]]
[[2, 2, 2], [2, 2, 2], [2, 1, 1]]
[[2, 2, 2], [2, 2, 2], [2, 1, 2]]
[[2, 2, 2], [2, 2, 2], [2, 2, 0]]
[[2, 2, 2], [2, 2, 2], [2, 2, 1]]
[[2, 2, 2], [2, 2, 2], [2, 2, 2]]



I'm believe there are several opportunities for optimization both in the
code and in the algorithm (for instance, it may be possible to take
advantage of repetition in the sub-matrices), but I won't be trying that
now.

Good luck with what you're doing,
Sean





More information about the Python-list mailing list