Write a Python function that calculates the inverse of a 2x2 matrix. Return ‘None’ if the matrix is not invertible.

Example:

Input: matrix = [[4, 7], [2, 6]]

Output:[[0.6, -0.7], [-0.2, 0.4]]

一个矩阵A,要求它的逆矩阵A-1,这就需要满足A * A-1 = I, I为单位矩阵。

因为是2x2的矩阵,比较简单,我们稍微算一下,就可以得到A-1每个元素是怎么换算过来的。然后代码嘛,就按照算好的公式直接计算就好了。

def inverse_2x2(matrix: list[list[float]]) -> list[list[float]]:  
 a = matrix[0][0]  
 b = matrix[0][1]  
 c = matrix[1][0]  
 d = matrix[1][1]  
 det = a * d - b * c  
 if det == 0:  
  return None  
 inverse =  [[1/det * d, -1/det * b],  
    [-1/det * c, 1/det * a]]  
 return inverse