nested for loop

Anton Vredegoor anton at vredegoor.doge.nl
Tue May 11 08:34:54 EDT 2004


wjb131 at web.de (Wolfgang Buechel) wrote:

>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:
>
>M=26
>   for a in range(M):
>      for b in range (M):
>         for c in range (M):
>            for d in range (M):
>                 matr = [[a,b],[c,d]]
>			(dosomething)

[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 (;-)

This question is very much related to the one in a thread below here
(titled "Inverse of int(s, base)?"). In fact with a small adaptation
that code can produce this kind of matrices:

from itertools import islice

def tobase(i,base,digits):
    R = []
    for j in xrange(digits):
        i,k = divmod(i,base)
        R.append(k)
    R.reverse()
    return R

def as_matrix(R,rows,cols):
    it = iter(R)
    return [list(islice(it,cols)) for i in xrange(rows)]
    
def test():
    for i in range(10):
        R = tobase(i,25,6)
        print as_matrix(R,3,2)

if __name__=='__main__':
    test()

Anton



More information about the Python-list mailing list