def readmat(lines): mat = [] for line in lines: parts = line.split(' ') parts = [int(p) for p in parts if p != ''] mat.append(parts) return mat def rowswap(mat, i, j): mat[i], mat[j] = mat[j], mat[i] def rowmult(mat, i, k): assert k != 0 mat[i] = [p * k for p in mat[i]] def rowdiv(mat, i, k): assert k != 0 assert not [p for p in mat[i] if p % k != 0] mat[i] = [p // k for p in mat[i]] def rowadd(mat, i, j, k): assert i != j for col in xrange(len(mat[i])): mat[i][col] += mat[j][col] * k def largestcommon(line): try: upper = min([abs(p) for p in line if p != 0]) except ValueError: return 1 for i in xrange(upper, 0, -1): for part in line: if not part % i == 0: break else: return i return 1 def solvematbycol(mat, col): mat.sort(key = lambda row, col = col: row[col] == 0) if col == 0: frow = 0 else: for i, line in enumerate(mat): if line[col - 1] == 0: frow = i break else: raise Exception, "lol" for i in xrange(frow + 1, len(mat)): if mat[i][col] == 0: continue rowmult(mat, i, mat[frow][col]) rowadd(mat, i, frow, - mat[i][col] // mat[frow][col]) def simplify(mat): for i, line in enumerate(mat): c = largestcommon(line) rowdiv(mat, i, c) def printmat(mat): print for line in mat: print ' '.join(["%3d" % i for i in line]) def testdata(file): lines = [] for line in open(file, 'r'): line = line.strip('\n') if line == '': break lines.append(line) return readmat(lines) if __name__ == '__main__': import sys a = testdata(sys.argv[1]) printmat(a) for col in range(len(a[0]) - 1): solvematbycol(a, col) simplify(a) printmat(a)