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

Andrei Kulakov ak@silmarill.org
Thu, 26 Jul 2001 21:15:30 -0400


On Thu, Jul 26, 2001 at 06:07:35PM -0700, Sheila King wrote:
> 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?

It works fine here:

>>> import mt
>>> a = mt.mtrx(2,5,.2)
>>> a.Display()
0.2 0.2 0.2 0.2 0.2
0.2 0.2 0.2 0.2 0.2

Python 2.1 on Debian linux.

> 
> --
> Sheila King
> http://www.thinkspot.net/sheila/
> http://www.k12groups.org/
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

-- 
Cymbaline: intelligent learning mp3 player - python, linux, console.
get it at: http://silmarill.org/cymbaline