[Tutor] Re: Verifying a data...

Prahlad Vaidyanathan slime@vsnl.net
Thu, 11 Jul 2002 11:21:33 +0530


Hi,

On Wed, 10 Jul 2002 Timothy M. Brauch spewed into the ether:
> I've run into a snag in one of my programs.  I am attempting to write a
> program for matrices, from scratch no less.  In part to help me learn python
> and in part so that features are not available that I do not want students
> to have.

    I have just recently written a matrix module, and I've put it up
here, in case you are interested :

    http://www.symonds.net/~prahladv/files/matrix.py

> So far, I can do many matrix manipulations; however, the part that is
> causing problems is verifying that what was entered was an actual valid
> matrix.  I want the matrix to be able to be a single row of integers (or
> floats now that I think about it), or a list of lists of integers.  Of
> course, I need all the rows to be the same length.  As long as it is a valid
> matrix, all my other operations work as expected.

    Well, Danny has pointed out the bug in your code, but I did
something which, IMHO, is a better way of verifying the matrix. In order
to verify the matrix, I've defined a __setitem__() method, like so :

"""
class Matrix :
    ...
    ...
    def __setitem__ (self, (row,column), value) :
        """Sets the value of the element.

        Note: Currently only accepts integers, floating point
              values, or complex numbers.
        """
        if type(value) not in [type(1), type(1.0), type(complex(1,1))] :
            raise TypeError, "Incorrect assignment of %s" % type(value)
        self.matrix[row][column] = value
"""

Now, this is how it works :

"""

$ python
Python 2.2 (#1, Jul 10 2002, 08:12:39)
[GCC 2.96 20000731 (Linux-Mandrake 8.0 2.96-0.48mdk)] on linux2
Type "help", "copyright", "credits" or "license" for more
information.
>>> import matrix
>>> a = matrix.Matrix() ## Initializes a 3x3 Null matrix
>>> a[1,2] = 1
>>> print a
[0, 0, 0]
[0, 0, 1]
[0, 0, 0]
>>> a[2,1] = "hello"
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "/home/prahlad/.python/matrix.py", line 91, in __setitem__
    raise TypeError, "Incorrect assignment of %s" % type(value)
TypeError: Incorrect assignment of <type 'str'>
>>>

"""

HTH,

pv.
-- 
Prahlad Vaidyanathan  <http://www.symonds.net/~prahladv/>

Gold's Law:
	If the shoe fits, it's ugly.