Inverse by row reduction

Row reduction finds the inverse of any invertible matrix, not only 2×2 ones.

What to build

Find the inverse of an n × n matrix with exact fractions, or say it is singular.

Requirements

  • Read n and the matrix.
  • Row-reduce the matrix next to the identity.
  • Print the inverse rows with fractions in lowest terms, or singular.

Input

A whole number n (1 to 4), then n lines of n whole numbers.

Output

The n rows of the inverse, entries separated by single spaces and written as whole numbers or fractions such as -3/2; or the word singular.

Constraints

Entries are between -9 and 9.

Example

Input:

2
4 7
2 6

Output:

3/5 -7/10
-1/5 2/5

Why it works

Each row operation is multiplication by an invertible matrix. If a sequence of operations turns A into I, then the same sequence applied to I produces A⁻¹. A column without a pivot means the determinant is 0 and no inverse exists.

Examples

Example 1 · Input
2
4 7
2 6
Expected output
3/5 -7/10
-1/5 2/5
Example 2 · Input
2
1 2
2 4
Expected output
singular

Prompts inside input() are ignored when checking, so input("n: ") is fine.

Hints

Hint 1

Write [A | I] and use row operations until the left half is the identity; the right half is then the inverse.

Hint 2

Use Fraction entries. If some column has no pivot, print `singular`.

Hint 3

Print each row with entries separated by single spaces, using `str` of each Fraction.

Solution

Show one correct solution (try it yourself first)
from fractions import Fraction

n = int(input())
a = [[Fraction(int(x)) for x in input().split()] for _ in range(n)]
m = [a[i] + [Fraction(1 if i == j else 0) for j in range(n)] for i in range(n)]
ok = True
for col in range(n):
    pivot = next((r for r in range(col, n) if m[r][col] != 0), None)
    if pivot is None:
        ok = False
        break
    m[col], m[pivot] = m[pivot], m[col]
    p = m[col][col]
    m[col] = [v / p for v in m[col]]
    for r in range(n):
        if r != col and m[r][col] != 0:
            f = m[r][col]
            m[r] = [x - f * y for x, y in zip(m[r], m[col])]
if ok:
    for row in m:
        print(*row[n:])
else:
    print("singular")

▶ Open this solution in the compiler, then press Visualize to watch it run step by step

Lesson: Determinants and inverses →