[Tutor] Baffled: why doesn't range work?

Sheila King sheila@thinkspot.net
Thu, 26 Jul 2001 18:07:35 -0700


OK, here I think I know what I'm doing...? Done enough Python now that I
feel pretty competent.

Well, surprise. I can't get something really simple to work. I know I'm
going to feel dumb when someone points out my error.

OK, here is a module, called matrixprog.py:

---------------------------------------------------
class mtrx:
    def __init__(self, numRows = 1, numCols = 1, initVal=0):
        self.numRows = numRows
        self.numCols = numCols
        self.data = {}
        if initVal != 0:
            for i in range(1, numRows + 1, 1):
                for j in range(1, numCols + 1, 1):
                    self.data[(i, j)] = initVal

    def Display(self):
        for i in range(1, self.numRows + 1, 1):
            for j in range(1, self.numCols + 1, 1):
                if self.data.has_key( (i, j) ):
                    print self.data[ (i, j) ],
                else:
                    print str(0),
            print
---------------------------------------------------

Here is an interactive session using the module:

---------------------------------------------------
>>> import matrixprog
>>> A = matrixprog.mtrx(2, 5, .2)
>>> A.Display()
0.2 0.2
0.2 0.2
>>> A.data
{(1, 6): 0.20000000000000001, (3, 6): 0.20000000000000001, (3, 1):
0.20000000000000001, (1, 1): 0.20000000000000001}
>>>
---------------------------------------------------

Now, something is very wrong. The matrix A should look like this:

0.2 0.2 0.2 0.2 0.2
0.2 0.2 0.2 0.2 0.2

Where did the six missing elements of my matrix go? I've tried a bunch
of different things, but I can't get this stupid matrix to insert all
the required elements. It seems to skip over most of them and just do
the four corners of the matrix?

--
Sheila King
http://www.thinkspot.net/sheila/
http://www.k12groups.org/