Before solving a system it helps to know what to expect: one answer, none or many.
What to build
For a square system, decide whether it has one solution, none or infinitely many.
Requirements
- Read n and the n rows of the augmented matrix (n + 1 numbers each).
- Compute the rank of the coefficient part and of the whole augmented matrix by elimination with exact fractions.
- Print
unique,noneorinfinite.
Input
A whole number n (1 to 5), then n lines of n + 1 whole numbers.
Output
One word: unique, none or infinite.
Constraints
All numbers are between -20 and 20.
Example
Input:
2
1 1 3
1 -1 1
Output:
unique
Why it works
Elimination turns the system into pivot rows. If the augmented matrix has more pivots than the coefficient matrix, some row reads 0 = c, so there is no solution. Equal ranks mean a solution exists, and it is unique exactly when the rank equals the number of unknowns.
Examples
2 1 1 3 1 -1 1
unique
2 1 2 3 2 4 7
none
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Do elimination with Fraction numbers and count the pivots: the rank of A and the rank of the augmented matrix.
Hint 2
If the ranks differ, there is no solution. If both equal n, there is one. If they are equal and less than n, there are infinitely many.
Hint 3
Rank of a matrix: for each column, look for a row below the current rank row with a non-zero entry.
Solution
Show one correct solution (try it yourself first)
from fractions import Fraction
n = int(input())
rows = [[Fraction(int(v)) for v in input().split()] for _ in range(n)]
def rank(m, cols):
m = [row[:] for row in m]
r = 0
for col in range(cols):
pivot = next((i for i in range(r, len(m)) if m[i][col] != 0), None)
if pivot is None:
continue
m[r], m[pivot] = m[pivot], m[r]
for i in range(len(m)):
if i != r and m[i][col] != 0:
factor = m[i][col] / m[r][col]
m[i] = [a - factor * b for a, b in zip(m[i], m[r])]
r += 1
return r
ra = rank(rows, n)
rb = rank(rows, n + 1)
if ra != rb:
print("none")
elif ra == n:
print("unique")
else:
print("infinite")
▶ Open this solution in the compiler, then press Visualize to watch it run step by step