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]])