[Tutor] Verifying a data...

Timothy M. Brauch tbrauch@mindless.com
Wed, 10 Jul 2002 19:01:25 -0400


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.

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.

What I have so far to verifiy, but does not work correctly, is:

def verify_matrix(mtrx):
## check if first item is integer
    if type(mtrx[0]) == type(1):
        ## if integer, all must integers
        for r in mtrx:
            if type(r) != type(1):
                return __dimensionError__('dimension mismatch in creation')
            else: return mtrx
    ## if first item not integer, must be a list
    elif type(mtrx[0]) == type([]):
    ## all lists must be same length
    ##I should probably check that list is made up of only ints as well
(later)
        length = len(mtrx[0])
        for r in mtrx:
            if len(r) != length:
                return __dimentionError__('dimension mismatch in creation')
            else: return mtrx
    else:
        print 'Invalid matrix'
        return None

I tried running this, and got:

Python 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit (Intel)] on win32
Type "copyright", "credits" or "license" for more information.
IDLE 0.8 -- press F1 for help
>>> import matrix
>>> M = matrix
>>> m = M.matrix([[1,2],[3,4]])
>>> m
[[1, 2], [3, 4]]
>>> M.display_matrix(m)
[1, 2]
[3, 4]
>>> a = M.matrix([1, 2, [3, 4]])
>>> M.display_matrix(a)
1
2
[3, 4]
>>>

Shouldn't I get a dimensionError when I create 'a'?

I really thought I was understanding this.. aargh.

 - Tim