Open the context
Choose the project folder and name the files or behavior involved.
Solve a square integer linear system of up to eight equations using exact fractions. Test a required row swap and a fractional solution, rejecting singular systems or mismatched dimensions while preserving the inputs.
Choose the project folder and name the files or behavior involved.
Describe the input, expected output and boundaries that must stay intact.
Review the proposed edits and any commands before relying on their result.
Compare actual behavior with the expected result. If a check fails, investigate it before applying more changes.
from fractions import Fraction
def solve_linear(matrix, rhs):
matrix, rhs = [tuple(row) for row in matrix], tuple(rhs)
n = len(matrix)
if not 1 <= n <= 8 or len(rhs) != n or any(len(row) != n for row in matrix):
raise ValueError("system.shape")
if any(type(v) is not int or abs(v) > 1000000 for row in matrix for v in row) or any(type(v) is not int or abs(v) > 1000000 for v in rhs):
raise ValueError("coefficient.range")
a = [[Fraction(v) for v in row] + [Fraction(rhs[i])] for i, row in enumerate(matrix)]
for col in range(n):
pivot = next((r for r in range(col, n) if a[r][col]), None)
if pivot is None:
raise ValueError("system.singular")
a[col], a[pivot] = a[pivot], a[col]
scale = a[col][col]
a[col] = [v / scale for v in a[col]]
for r in range(n):
if r != col:
factor = a[r][col]
a[r] = [x - factor * y for x, y in zip(a[r], a[col])]
return [row[-1] for row in a]The example is a starting point for a real project, not a claim that generated code is already tested. Adjust paths, dependencies and expected behavior to match your application.