<jupyter_start><jupyter_text>Matrix inversion using Laplace expansion<jupyter_code>matrix = [[1, 2, 0],
          [4, 5, 6],
          [7, 8, 9]]
def first_minor(matrix, row_exclusion, column_exclusion):
  return [[matrix[row_id][column_id] for
           column_id in
           range(len(matrix[row_id])) if
           column_id != column_exclusion] for
          row_id in range(len(matrix)) if
          row_id != row_exclusion]
def diagonal_mirror(matrix):
  return [[matrix[column_id][row_id] for
           column_id in range(len(matrix[row_id]))] for
          row_id in range(len(matrix))]
def determinant(matrix):
  # Undefined behavior will occur when supplied a non-square matrix.
  
  def factor_pair(matrix, scalar_column):
    scalar = matrix[0][scalar_column]
    
    minor = first_minor(matrix, 0, scalar_column)
    
    return scalar, minor
  
  def determinant_term(scalar_column):
    scalar, minor = factor_pair(matrix, scalar_column)

    if len(minor) == 1:
      return scalar * minor[0][0]
    else:
      return scalar * determinant(minor)
    
  return sum([determinant_term(term) * ((-1) ** (2 - (term % 2))) for term in range(len(matrix))])

determinant(matrix)
def invert(matrix):
  inverted_determinant = 1 / determinant(matrix)
  
  determinant_matrix = [[determinant(first_minor(matrix, row_id, column_id)) * ((-1) ** (2 - (column_id + row_id * len(matrix[row_id])) % 2)) for
                         column_id in range(len(matrix[row_id]))] for
                        row_id in range(len(matrix))]
  
  return diagonal_mirror([[inverted_determinant * column for column in row] for row in determinant_matrix])

invert(matrix)
import numpy as np

np.linalg.inv(matrix)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.11829197922677438, 'fraction_numerical': 0.012117714945181766, 'mean_word_length': 3.367758186397985, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '93069', 'license': 'MIT', 'n_tokens_mistral': 593, 'n_tokens_neox': 558, 'n_words': 136, 'path': 'Matrix_Inversion.ipynb', 'repo_name': 'hinsley/colabs', 'size': '1733'}