File size: 751 Bytes
93237a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
from fractions import Fraction as F
A = [[1, 1, 1], [2, -1, 1], [1, 2, -1]]
b = [6, 3, 2]
m = [[F(value) for value in row] + [F(rhs)] for row, rhs in zip(A, b)]
for col in range(3):
    pivot = next(r for r in range(col, 3) if m[r][col] != 0)
    m[col], m[pivot] = m[pivot], m[col]
    scale = m[col][col]
    m[col] = [value / scale for value in m[col]]
    for r in range(3):
        if r != col:
            factor = m[r][col]
            m[r] = [v - factor * p for v, p in zip(m[r], m[col])]
solution = [m[i][-1] for i in range(3)]
assert all(sum(F(a) * x for a, x in zip(row, solution)) == rhs for row, rhs in zip(A, b))
result = {"solution": [str(x) for x in solution]}
import json
print(json.dumps(result, ensure_ascii=False, sort_keys=True))