nested for loop
Dan Bishop
danb_83 at yahoo.com
Sun May 23 18:07:22 EDT 2004
wjb131 at web.de (Wolfgang Buechel) 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).
>
> To produce them, first I wrote a fourfold nested for loop:
...
> Then I had a look in comp.lang.python and found:
>
>
> for (a,b,c,d) in [(x,y,z,t) for x in range(M)
> for y in range(M)
> for z in range(M)
> for t in range(M)] :
> matr = [[a,b],[c,d]]
This may be shorter, but it's slower. Your old code took "only" 1.5
seconds to run on this computer, but the new way takes 3.5 seconds.
What you *can* do to make your code faster (if you don't change matr
once it's created) is to precompute the 676 possible matrix rows.
ELEMENT_RANGE = range(26)
MATRIX_ROWS = [[x, y] for x in ELEMENT_RANGE
for y in ELEMENT_RANGE]
for row1 in MATRIX_ROWS:
for row2 in MATRIX_ROWS:
matr = [row1, row2]
That takes only 532 ms -- almost 3 times faster than the original.
More information about the Python-list
mailing list