fork download
  1. # Name : Ananda Das;
  2. # ID : 230241053;
  3. # Lab : 3 , Problem : 04;
  4.  
  5. def get_matrix_minor(matrix, i, j):
  6. return [row[:j] + row[j+1:] for row in (matrix[:i] + matrix[i+1:])]
  7.  
  8. def determinant(matrix):
  9. if len(matrix) == 1:
  10. return matrix[0][0]
  11. if len(matrix) == 2:
  12. return matrix[0][0]*matrix[1][1] - matrix[0][1]*matrix[1][0]
  13. det = 0
  14. for c in range(len(matrix)):
  15. det += ((-1)**c) * matrix[0][c] * determinant(get_matrix_minor(matrix, 0, c))
  16. return det
  17.  
  18. def replace_column(matrix, col_index, new_col):
  19. return [
  20. [new_col[row] if col == col_index else matrix[row][col] for col in range(len(matrix))]
  21. for row in range(len(matrix))
  22. ]
  23.  
  24. def transpose(matrix):
  25. return [[matrix[j][i] for j in range(len(matrix))] for i in range(len(matrix))]
  26.  
  27. def cofactor_matrix(matrix):
  28. cofactors = []
  29. for i in range(len(matrix)):
  30. row = []
  31. for j in range(len(matrix)):
  32. minor = get_matrix_minor(matrix, i, j)
  33. row.append(((-1) ** (i + j)) * determinant(minor))
  34. cofactors.append(row)
  35. return cofactors
  36.  
  37. def inverse_matrix(matrix):
  38. det = determinant(matrix)
  39. if det == 0:
  40. return None
  41. cofactors = cofactor_matrix(matrix)
  42. adjoint = transpose(cofactors)
  43. return [[adjoint[i][j] / det for j in range(len(matrix))] for i in range(len(matrix))]
  44.  
  45. def cramer_solver(A, B):
  46. n = len(A)
  47. detA = determinant(A)
  48. if detA == 0:
  49. return None, 0
  50. solution = []
  51. for i in range(n):
  52. Ai = replace_column(A, i, B)
  53. xi = determinant(Ai) / detA
  54. solution.append(xi)
  55. return solution, detA
  56.  
  57. n = int(input("Enter the order of square matrix: "))
  58. print("Enter coefficients of matrix A:")
  59. A = [list(map(float, input().split())) for _ in range(n)]
  60.  
  61. print("Enter constants of vector B:")
  62. B = list(map(float, input().split()))
  63.  
  64. solution, detA = cramer_solver(A, B)
  65. print(f"\nDeterminant of A: {detA:.3f}")
  66.  
  67. if detA == 0:
  68. print("Matrix is singular; the system is not uniquely solvable.")
  69. exit()
  70.  
  71. print("\nThe solution using Cramer's Rule:")
  72. for i, val in enumerate(solution):
  73. print(f"x{i+1} = {val:.6f}")
  74.  
  75. invA = inverse_matrix(A)
  76. print("\nInverse of matrix A:")
  77. for row in invA:
  78. print(" ".join(f"{val:.4f}" for val in row))
  79.  
Success #stdin #stdout 0.12s 14192KB
stdin
2
2 5
-3 1
11 -4
stdout
Enter the order of square matrix: Enter coefficients of matrix A:
Enter constants of vector B:

Determinant of A: 17.000

The solution using Cramer's Rule:
x1 = 1.823529
x2 = 1.470588

Inverse of matrix A:
0.0588 -0.2941
0.1765 0.1176