这是我的Matrix类的定义
class Matrix(object):
# Constructor
def __init__(self, grid):
self.g = grid
self.h = len(grid)
self.w = len(grid[0])
def inverse(self):
"""
Calculates the inverse of a 1x1 or 2x2 Matrix.
"""
if not self.is_square():
raise(ValueError, "Non-square Matrix does not have an inverse.")
if self.h > 2:
raise(NotImplementedError, "inversion not implemented for matrices larger than 2x2.")
# TODO - your code here
invert = zeroes(1,1)
if self.h == 1:
invert[0][0]=(1/self.g[0][0])
elif self.h == 2:
# Calculate the inverse of the square 1x1 or 2x2 matrix.
a = self.g[0][0]
b = self.g[0][1]
c = self.g[1][0]
d = self.g[1][1]
factor = 1 / (a * d - b * c)
invert = [[d, -b],[-c, a]]
for i in range(self.h):
for j in range(self.w):
invert[i][j] = factor * invert[i][j]
return Matrix(invert)
我收到的错误是TypeError:“矩阵”类型的对象没有len()。但是,结果需要为矩阵大小1x1的倒数。