LoginSignup
4
3

More than 3 years have passed since last update.

掃き出し法の途中式をPythonでTeX出力する

Last updated at Posted at 2020-06-25

掃き出し法,めんどい

途中式が必要なのめんどくさすぎる.TeXで毎回描くのもだりい.
退屈なのでPythonで解決.

ソースコード

print("&=" + tex_print(a) + r"\\")

ここのところ変えてあげるとTeX用にカスタムしやすいよ

sweep.py
from fractions import Fraction
import copy


def swap_rows(mat_list, num1, num2):
    mat_list[num1], mat_list[num2] = mat_list[num2], mat_list[num1]


def check_chaneg(a, b):
    if not a == b:
        print("&=" + tex_print(a) + r"\\")


def tex_print(mat_list):
    tex_txt = r"\left(\begin{array}{" + "c" * len(mat_list[0]) + r"}@\end{array}\right)"
    inner_txt = ""
    for l in mat_list:
        line_txt = ""
        for el in l:
            if "/" in str(el):
                line_txt += r"\frac{" + str(el).split("/")[0] + "}{" + str(el).split("/")[1] + "}"
            else:
                line_txt += str(el)
            line_txt += "&"
        line_txt = line_txt[: -1]
        line_txt += r"\\"
        inner_txt += line_txt
    tex_txt = tex_txt.replace("@", inner_txt)
    return tex_txt


rows = int(input("rows:"))
columns = int(input("columns:"))

mat_list = []
for _ in range(rows):
    mat_list.append(list(map(int, input().split())))

print(mat_list)
now_row = 0  # 現在何列目
pre_mat = []
for n in range(columns):
    # 行入れ替え
    pre_mat = copy.deepcopy(mat_list)
    zero_flag = True
    for i in range(now_row, rows):
        if not mat_list[i][n] == 0:
            swap_rows(mat_list, now_row, i)
            zero_flag = False
            break
    if zero_flag:
        continue
    check_chaneg(mat_list, pre_mat)

    # n列目を1にする
    pre_mat = copy.deepcopy(mat_list)
    temp = [0] * columns
    for c in range(columns):
        temp[c] = Fraction(mat_list[now_row][c], mat_list[now_row][n])
    mat_list[now_row] = temp
    check_chaneg(mat_list, pre_mat)

    # now_row以外のn列目を0にする
    pre_mat = copy.deepcopy(mat_list)
    for i in range(0, rows):
        if i == now_row:
            continue
        if not mat_list[i][n] == 0:
            temp = [0] * columns
            for c in range(columns):
                temp[c] = mat_list[i][c] - mat_list[i][n] * mat_list[now_row][c]
            mat_list[i] = temp
    check_chaneg(mat_list, pre_mat)

    now_row += 1
    if now_row > rows:
        break
check_chaneg(mat_list, 0)

使ってみた

途中式を出すことが目的のコードだから結果だけほしいなら最適化されたコードか,WolframAlphaでやれ.
今回のソースコードはalign環境に貼り付ける前提で作った.

4
3
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
3