Write a Python function that transforms a given matrix A using the operation T−1AS, where T and S are invertible matrices. The function should first validate if the matrices T and S are invertible, and then perform the transformation. In cases where there is no solution return -1

Example: Input:A = [[1, 2], [3, 4]], T = [[2, 0], [0, 2]], S = [[1, 1], [0, 1]]Output:[[0.5,1.5],[1.5,3.5]]

首先是确定T和S是否可逆,只要保障这两个矩阵的行列式不为0就可以了。然后就是按照要求进行矩阵的相乘。在numpy中,用的是@这个符号。

import numpy as np  
  
def transform_matrix(A: list[list[int|float]], T: list[list[int|float]], S: list[list[int|float]]) -> list[list[int|float]]:  
    A = np.array(A, dtype=float)  
    T = np.array(T, dtype=float)  
    S = np.array(S, dtype=float)  
      
    if np.linalg.det(T) == 0:  
        return -1  
    if np.linalg.det(S) == 0:  
        return -1  
          
    iT = np.linalg.inv(T)  
    transformed_matrix = iT @ A @ S  
    return transformed_matrix.tolist()