from fractions import Fraction
from sympy import *
g, t, i, c = symbols('g t i c')
out = solve([
g * Fraction(1, 1) + t * Fraction(1, 1) - Fraction(1, 2),
g * Fraction(1, 1) + i * Fraction(1, 1) - Fraction(1, 3),
g * Fraction(1, 1) + c * Fraction(1, 1) - Fraction(1, 4),
g * Fraction(1, 1) + t * Fraction(1, 1) + i * Fraction(1, 1) + c * Fraction(1, 1) - Fraction(1, 1),
], [g, t, i, c])
out[g] # -> Fraction(1, 24)
def gauss_elimination(m):
'''mは[g, t, i, c, value]というベクトルを4本持つ行列'''
n = len(m)
# 前進消去
for i in range(n):
v = m[i][i]
if v == 0:
# ゼロ以外の値を持つ行と交換する
for k in range(i + 1, n):
if m[k][i] != 0:
m[i], m[k] = m[k], m[i]
v = m[i][i]
break
for j in range(n + 1):
m[i][j] /= v
for k in range(i + 1, n):
v = -m[k][i]
for j in range(n + 1):
m[k][j] += m[i][j] * v
# 後退代入
for i in range(n-1, 0, -1):
v = m[i][i]
m[i][i] /= v
m[i][n] /= v
for k in range(i - 1, -1, -1):
v2 = m[k][i] * m[i][n]
m[k][n] -= v2
m[k][i] = Fraction(0, 1)
return m