Re: How to do multi-dimensional arrays?

Aaron Watters (aaron@funcity.njit.edu)
Fri, 20 Jan 1995 14:49:27 GMT

Steve Majewski writes that a 2d array can be initialized without
shared reference problems thusly:

>arr = map( lambda x: [x]*4, [0]*4 )

but has problems with

>>>> XXX = map( lambda x: [x]*4, map( lambda x: [x]*4, [0]*4 ) )

which produces update anomalies:

>>> XXX[1][2][3] = 123
>>> XXX
[[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]], [[0, 0, 0, 123], [0,
0, 0, 123], [0, 0, 0, 123], [0, 0, 0, 123]], [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0,
0, 0], [0, 0, 0, 0]], [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0,
0, 0, 0]]]

This can be fixed by putting one lambda inside the other, thusly:

>>> YYY = map((lambda x: (map(lambda y: [y]*4,[0]*4))),[0]*4)

where

>>> YYY[1][2][3] = 231

only changes the one entry, as expected.

==Non-masochists, please delete this article NOW =======

And for the functional programming freaks out there here is a
matrix multiplication function in native python that follows
the f.p. style (except for initializations, which could be omitted
if you really insist).

def mmultfp(m1,m2):
m2rows,m2cols = len(m2),len(m2[0])
m1rows,m1cols = len(m1),len(m1[0])
ri = range( m1rows )
rj = range( m2cols )
rk = range( m1cols )
if m1cols != m2rows: raise IndexError, "matrices don't match"
return map( lambda i, m1=m1, m2=m2, rj=rj, rk=rk: (
map ( lambda j, m1i=m1[i], m2=m2, rk=rk: (
reduce ( lambda v, k, j=j, m1i=m1i, m2=m2: (
v + m1i[k]*m2[k][j]),
rk, 0)), rj )), ri )

[Note that all non-global variables have to be passed inside the
lambdas via default arguments. This is irritating, but I think fixing
it would be more trouble and expense than it's worth.]

Of 4 implementations this is the slowest yet I've come up with.
Not recommended, unless you fret a lot about "beauty" and "elegance"
and "the Von Neumann bottleneck" and so forth.
Aaron Watters
Department of Computer and Information Sciences
New Jersey Institute of Technology
University Heights
Newark, NJ 07102
phone (201)596-2666
fax (201)596-5777
home phone (908)545-3367
email: aaron@vienna.njit.edu

Anyone who ever said "What's the Big Idea?" knows that Big Ideas
are usually bad ones. -P.J. O'Rourke, _All the Trouble in The World_