嘿,我刚才想知道python的新手,在提交之前我做的是正确的吗?
inverse = []
matrix = [[1, 2] , [3, 4]]
if len (matrix) != len(matrix [0]):
raised (‘The matrix must be square’)
答案 0 :(得分:2)
您需要引发错误类型并更改逻辑以确定矩阵是否为正方形:
inverse = []
matrix = [[1, 2], [3, 4]]
if len(matrix) != len(matrix[0]) and len(set(map(len, matrix))) != 1:
raise AttributeError('The matrix must be square') #or error of your choice
但是,如果您希望生成自定义错误,则可以从Exception继承并覆盖__str__
:
class MatrixLenError(Exception):
pass
matrix = [[1, 2], [3, 4]]
if len(matrix) != len(matrix[0]) and len(set(map(len, matrix))) != 1:
raise MatrixLenError('The matrix must be square')
答案 1 :(得分:2)
尽管您的代码有效,但它不适用于[[1,2], [1,2,3]]
等矩阵。
首先,将此逻辑封装在一个方法中:
def is_squared(matrix):
# Check that all rows have the correct length, not just the first one
return all(len(row) == len(matrix) for row in matrix)
然后,您可以:
inverse = []
matrix = [[1,2], [3,4]]
if not is_squared(matrix):
raise AttributeError("The matrix must be squared")