nested for loop
Sean Ross
sross at connectmail.carleton.ca
Mon May 10 23:09:20 EDT 2004
"Sean Ross" <sross at connectmail.carleton.ca> wrote in message
news:VDWnc.21679$FH5.581779 at news20.bellglobal.com...
[snip]
> # 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)]
[snip]
> [I] 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.
Looks like I'll be trying it now after all:
def nXn_matrices2(n, elements):
for m in sequences(n, list(sequences(n, elements))):
yield m
This is slightly faster than the first version, but it has more overhead
since it builds a list of the submatrices. That could be problem. It can
probably be avoided, but I haven't figured out how to do it just yet. We'll
see what happens.
Sean
More information about the Python-list
mailing list