[Edu-sig] Example exercise for learning Python

Kirby Urner pdx4d@teleport.com
Tue, 30 May 2000 11:58:23 -0700


Here's an exercise for learning Python syntax -- a subclass
of "multiple ways of getting the same result" (in general
a useful approach).

Some of you may have seen this as a thread on comp.lang.python
where I asked for ideas for compactly generating a list of n 
lists with m 0s in each.

Or, as a pictogram:

    m m m m m m 
n [[0,0,0,0,0,0],
n  [0,0,0,0,0,0],
n  [0,0,0,0,0,0],
n  [0,0,0,0,0,0]]

Example:

 >>> output = zeromatrix(3,3)  # 3 lists of 3 members each
 >>> output
 [[0,0,0],[0,0,0],[0,0,0]]
 >>> output = zeromatrix(3,4)  # 3 lists of 4 members each
 >>> output
 [[0,0,0,0],[0,0,0,0],[0,0,0,0]]


   def zeromatrix(n,m):
        # my first attempt
        output = [0]*n
        for i in range(n): output[i]=[0]*m
        return output


   def zeromatrix(n,m):
        # slightly better
        output = []
        for i in range(n): output.append([0]*m)
        return output

   from copy import copy
   def zeromatrix (n, m):
        # from Alex, interesting
        line = n * [0]
        matrix = map (copy, m * [line])
        return matrix

   def zeroMatrix(rows, cols):
        # from Edward, getting shorter 
        return map(lambda x, c=cols: [0]*c, [0]*rows)

   def zeromatrix(m, n):
        # from Tamito Kajiyama, concise to the 
        # point of cryptic (fun!)
        return map(lambda x: [0]*x, [n]*m)

Of course some people just told me to use NumPy's zero 
matrix function, but that'd be missing the experience 
of rolling your own.

Note that the follow WILL NOT work:

   def zeromatrix(n,m):
        return [[0]*m]*n

because it's actually reusing the same object n times.  
So, using the above def, if you go:

 >>> output = zeromatrix(3,3)
 >>> output
 [[0,0,0],[0,0,0],[0,0,0]]
 >>> output[0][0] = 5
 >>> output
 [[5, 0, 0], [5, 0, 0], [5, 0, 0]]

... which is NOT the behavior I want.

Kirby