목차

matrix.py

imports and globals

from __future__ import annotations
import operator

MatType = list[list[float]]

matmul

코드

# N matmul
# I {"version": "1.1", "import":["operator"], "const": ["MatType"]}
def matmul(mat_a: Matrix, mat_b: Matrix, mod: int = 0) -> Matrix:
    if mod == 0:
        return [
            [sum(map(operator.mul, a_row, b_col)) for b_col in zip(*mat_b)]
            for a_row in mat_a
        ]
    return [
        [sum(map(operator.mul, a_row, b_col)) % mod for b_col in zip(*mat_b)]
        for a_row in mat_a
    ]

설명

이 코드를 사용하는 문제

Nothing found

matpow

코드

# N matpow
# I {"version": "1.1", "const": ["MatType"], "func": ["matmul"]}
def matpow(mat: Matrix, n: int, mod: int = 0) -> MatType:
    res = [[0] * len(mat) for _ in mat]
    for i, row in enumerate(res):
        row[i] = 1
    m = [row[:] for row in mat]
    for c in bin(n)[:1:-1]:
        if c == '1':
            res = matmul(res, m, mod)
        m = matmul(m, m, mod)
    return res

설명

이 코드를 사용하는 문제

Nothing found

Matrix

코드

# N Matrix
# I {"version": "0.2", "future": ["annotations"], "func": ["identity", "matmul", "matpow"]}
class Matrix:
    """A simple wapper class of matrix operation functions."""

    __slots__ = ('mat',)
    _mod = 0

    @classmethod
    def set_mod(cls, mod: int):
        cls._mod = mod

    def __init__(self, mat_or_size):
        if isinstance(mat_or_size, int):
            self.mat = [[0] * mat_or_size for _ in range(mat_or_size)]
        else:
            self.mat = [r[:] for r in mat_or_size]

    @classmethod
    def identity(cls, size: int):
        mat = [[0] * size for _ in range(size)]
        for i, row in enumerate(mat):
            row[i] = 1
        return cls(mat)

    def __getitem__(self, row: int):
        return self.mat[row]

    def __matmul__(self, other: Matrix):
        return Matrix(matmul(self.mat, other.mat, self._mod))

    def __pow__(self, n, mod=0):
        return Matrix(matpow(self.mat, n, (mod or self._mod)))

    def __mod__(self, mod):
        return Matrix([[item % mod for item in row] for row in self.mat])

설명

이 코드를 사용하는 문제

Nothing found