0
def matrixDimensions(m): 
    """ function that returns the dimensions of a matrix. """

    mRowNum= len(m) # this is the number of rows
    mColNum=len(m[0])# this is the size of columns in row 1
    i=1
    j=1
    if mRowNum ==1:  # if there is only one row , don't need to check for identical columns
        return "This is a %ix%i matrix." %(mRowNum,mColNum)
    ColNum=len(m[i])# # this is the size of columns in row 2
    if mRowNum>1:# this is where you need to check all the columns are identical
        while i< mRowNum: 
            i+=1
            if len(m[j])== len(m[0]):   
                print (i,j,mRowNum,ColNum,m[j],len(m[j]))
                j+=1
                continue
            elif len(m[j])!= len(m[0]):
                return  'This is not a valid matrix.'
    return "This is a %ix%i matrix." %(mRowNum,mColNum)     

より単純なロジックが必要であり、ネストされたリストをどのようにチェックしますか。たとえば、これは有効なマトリックスではないと思いますが、このテストに合格します。

([ [1,4, 3], [4,0,21],[3,4,[5,7]],[1,2,3],[1,2,3]])             
4

1 に答える 1

1

You could try something like this instead:

def are_int(iterable):
    return all(isinstance(i, int) for i in iterable)

def matrix_dimensions(matrix):
    col = len(matrix[0])
    if not all(len(l) == col and are_int(l) for l in matrix):
        return 'This is not a valid matrix'
    else:
        return len(matrix), col

m = [[1,4,3], [4,0,21], [3,4,[5,7]], [1,2,3], [1,2,3]]
l = [[1,4,3], [4,0,21], [3,4,7], [1,2,3], [1,2,3]]

print(matrix_dimensions(m))
print(matrix_dimensions(l))

Output:

This is not a valid matrix
(5, 3)
于 2013-05-29T11:43:43.370 に答える