TestDrivenCode.com
0

Invert a matrix

by Anonymous User #86
Signature
def invert(matrix: list[list[float]]) -> list[list[float]]:
Test Code
import random def transpose(matrix: list[list[float]]) -> list[list[float]]: return [list(row) for row in zip(*matrix)] def dot(a: list[float], b: list[float]) -> float: return sum(x * y for x, y in zip(a, b)) def multiply(a: list[list[float]], b: list[list[float]]) -> list[list[float]]: return [[dot(row, col) for col in transpose(b)] for row in a] def identity_matrix(n: int) -> list[list[float]]: return [[float(i == j) for j in range(n)] for i in range(n)] def assert_close(a: list[list[float]], b: list[list[float]], tol: float = 1e-6): for i in range(len(a)): for j in range(len(a[0])): if abs(a[i][j] - b[i][j]) > tol: raise AssertionError(f"Values at ({i}, {j}) differ: {a[i][j]} vs {b[i][j]}") def copy(matrix: list[list[float]]) -> list[list[float]]: return [row[:] for row in matrix] def test_matrix(matrix: list[list[float]]) -> None: inverted_matrix = invert(copy(matrix)) # Check if the product of the original and inverted matrix is the identity matrix product = multiply(matrix, inverted_matrix) identity = identity_matrix(len(matrix)) assert_close(product, identity) test_matrix([[2]]) test_matrix([[1, 2], [3, 4]]) test_matrix([[4, 7], [2, 6]]) test_matrix([[2, 3, 1], [1, 2, 3], [3, 1, 2]]) test_matrix([[1, 2, 3], [0, 1, 4], [5, 6, 0]]) test_matrix([[0, 0, 1], [0, 1, 0], [1, 0, 0]]) test_matrix([[0, 1, 0], [0, 0, 1], [1, 0, 0]]) test_matrix([[1, 0, 0], [0, 0, 1], [0, 1, 0]]) test_matrix([[0, 1, 0], [1, 0, 0], [0, 0, 1]]) test_matrix([[-2, 2, -1], [6, -6, 7], [3, -8, 4]]) test_matrix([[0.02, 0.01, 0, 0], [1, 2, 1, 0], [0, 1, 2, 1], [0, 0, 100, 200]]) for n in range(2, 50): matrix = [[random.uniform(-10, 10) for _ in range(n)] for _ in range(n)] test_matrix(matrix)
Description

Given a matrix as a list of lists of floats, return an inverted matrix.

Submit a Solution

def invert(matrix: list[list[float]]) -> list[list[float]]:

Fastest Solutions

0
Solution by Anonymous User #90 (0.7 seconds)
def invert(matrix: list[list[float]]) -> list[list[float]]: """ Return the inverse of a square matrix using Gaussian elimination with partial pivoting. The input matrix is not modified. """ n = len(matrix) if any(len(row) != n for row in matrix): raise ValueError("Only square matrices can be inverted") # Build the augmented matrix [A | I] aug: list[list[float]] = [ row[:] + [float(i == j) for j in range(n)] for i, row in enumerate(matrix) ] for col in range(n): # ---- Partial pivoting ---- # Find the row with the largest absolute value in the current column pivot_row = max(range(col, n), key=lambda r: abs(aug[r][col])) if abs(aug[pivot_row][col]) < 1e-15: raise ValueError("Matrix is singular or near‑singular") # Swap the current row with the pivot row (if needed) if pivot_row != col: aug[col], aug[pivot_row] = aug[pivot_row], aug[col] # ---- Normalize pivot row ---- pivot_val = aug[col][col] inv_pivot = 1.0 / pivot_val aug[col] = [x * inv_pivot for x in aug[col]] # ---- Eliminate other rows ---- for r in range(n): if r == col: continue factor = aug[r][col] if factor == 0.0: continue aug[r] = [ aug[r][c] - factor * aug[col][c] for c in range(2 * n) ] # Extract the right half of the augmented matrix – this is the inverse inverse = [row[n:] for row in aug] return inverse
0
Solution by Anonymous User #88 (0.7 seconds)
def invert(matrix: list[list[float]]) -> list[list[float]]: """ Return the inverse of a square matrix using Gaussian elimination with partial pivoting. The input matrix is not modified. """ n = len(matrix) if any(len(row) != n for row in matrix): raise ValueError("Only square matrices can be inverted") # Build the augmented matrix [A | I] aug: list[list[float]] = [ row[:] + [float(i == j) for j in range(n)] for i, row in enumerate(matrix) ] for col in range(n): # ---- Partial pivoting ---- # Find the row with the largest absolute value in the current column pivot_row = max(range(col, n), key=lambda r: abs(aug[r][col])) if abs(aug[pivot_row][col]) < 1e-15: raise ValueError("Matrix is singular or near‑singular") # Swap the current row with the pivot row (if needed) if pivot_row != col: aug[col], aug[pivot_row] = aug[pivot_row], aug[col] # ---- Normalize pivot row ---- pivot_val = aug[col][col] inv_pivot = 1.0 / pivot_val aug[col] = [x * inv_pivot for x in aug[col]] # ---- Eliminate column entries in other rows ---- for r in range(n): if r == col: continue factor = aug[r][col] if factor == 0.0: continue # row_r = row_r - factor * pivot_row aug[r] = [ aug[r][c] - factor * aug[col][c] for c in range(2 * n) ] # Extract the right half of the augmented matrix: this is A⁻¹ inverse = [row[n:] for row in aug] return inverse

New Solutions

0
Solution by Anonymous User #90 (0.7 seconds)
def invert(matrix: list[list[float]]) -> list[list[float]]: """ Return the inverse of a square matrix using Gaussian elimination with partial pivoting. The input matrix is not modified. """ n = len(matrix) if any(len(row) != n for row in matrix): raise ValueError("Only square matrices can be inverted") # Build the augmented matrix [A | I] aug: list[list[float]] = [ row[:] + [float(i == j) for j in range(n)] for i, row in enumerate(matrix) ] for col in range(n): # ---- Partial pivoting ---- # Find the row with the largest absolute value in the current column pivot_row = max(range(col, n), key=lambda r: abs(aug[r][col])) if abs(aug[pivot_row][col]) < 1e-15: raise ValueError("Matrix is singular or near‑singular") # Swap the current row with the pivot row (if needed) if pivot_row != col: aug[col], aug[pivot_row] = aug[pivot_row], aug[col] # ---- Normalize pivot row ---- pivot_val = aug[col][col] inv_pivot = 1.0 / pivot_val aug[col] = [x * inv_pivot for x in aug[col]] # ---- Eliminate other rows ---- for r in range(n): if r == col: continue factor = aug[r][col] if factor == 0.0: continue aug[r] = [ aug[r][c] - factor * aug[col][c] for c in range(2 * n) ] # Extract the right half of the augmented matrix – this is the inverse inverse = [row[n:] for row in aug] return inverse
0
Solution by Anonymous User #88 (0.7 seconds)
def invert(matrix: list[list[float]]) -> list[list[float]]: """ Return the inverse of a square matrix using Gaussian elimination with partial pivoting. The input matrix is not modified. """ n = len(matrix) if any(len(row) != n for row in matrix): raise ValueError("Only square matrices can be inverted") # Build the augmented matrix [A | I] aug: list[list[float]] = [ row[:] + [float(i == j) for j in range(n)] for i, row in enumerate(matrix) ] for col in range(n): # ---- Partial pivoting ---- # Find the row with the largest absolute value in the current column pivot_row = max(range(col, n), key=lambda r: abs(aug[r][col])) if abs(aug[pivot_row][col]) < 1e-15: raise ValueError("Matrix is singular or near‑singular") # Swap the current row with the pivot row (if needed) if pivot_row != col: aug[col], aug[pivot_row] = aug[pivot_row], aug[col] # ---- Normalize pivot row ---- pivot_val = aug[col][col] inv_pivot = 1.0 / pivot_val aug[col] = [x * inv_pivot for x in aug[col]] # ---- Eliminate column entries in other rows ---- for r in range(n): if r == col: continue factor = aug[r][col] if factor == 0.0: continue # row_r = row_r - factor * pivot_row aug[r] = [ aug[r][c] - factor * aug[col][c] for c in range(2 * n) ] # Extract the right half of the augmented matrix: this is A⁻¹ inverse = [row[n:] for row in aug] return inverse