Теперь мне нужно перегрузить [], чтобы я мог читайте и присваивайте значения определенным ячейкам матрицы без прямого обращения к базовому списку из внешней области.
Итак, вот код:
Код: Выделить всё
from fractions import Fraction
def is_finite_decimal_denominator(n):
"""
:param n: denominator
:return: True if the denominator's factors are only 2 and 5
"""
number = n
while number != 1:
divisible_by_5 = (number % 5 == 0)
divisible_by_2 = (number % 2 == 0)
if not divisible_by_2 and not divisible_by_5:
return False
if divisible_by_2:
number = number // 2
else:
number = number // 5
return True
def fraction_to_string(fraction):
"""
:param fraction: print the fraction as a finite decimal one if possible
:return: void
"""
if fraction.denominator == 1:
return str(fraction.numerator)
if is_finite_decimal_denominator(fraction.denominator):
return str(fraction.numerator / fraction.denominator)
else:
return f"{fraction.numerator}/{fraction.denominator}"
class Matrix_LA:
def __init__(self, *arg):
self.M = []
for line in arg:
self.M.append(list(map(Fraction, line.split())))
self.n_rows = len(arg)
self.n_cols = len(self.M[0])
self.space = 8
def __str__(self):
str_mtrx = '+' + '-' * (self.n_cols * self.space) + '+\n'
for line in self.M:
str_mtrx += "|"
for num in line:
str_mtrx += f"{fraction_to_string(num): ^{self.space}}"
str_mtrx += "|\n"
str_mtrx += '+' + '-' * (self.n_cols * self.space) + '+\n'
return str_mtrx
def __getitem__(self, n):
return self.M[n]
x = Matrix_LA("1/7 2 ", "3 4")
print(x, x.M)
x[1][1] = Fraction(1, 7)
print(x, x.M)
Подробнее здесь: https://stackoverflow.com/questions/785 ... em-defined