Skip to content
Open

Dz11 #11

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 0 additions & 9 deletions new_sem11_oop/dz1.py

This file was deleted.

127 changes: 127 additions & 0 deletions new_sem11_oop/dz1_matrix.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
# Добавьте ко всем задачам с семинара строки документации и методы вывода информации на печать.

# Создайте класс Матрица. Добавьте методы для:
# - вывода на печать,
# - сравнения, (если равны: одинаковый размер, количество элементов)
# - сложения, (если они равны)
# - *умножения матриц (если кол-во столбцов одной мартицы равно кол-ву строк другой матрицы)

class Matrix:
"""Класс Матрица. Создаётся из списка списков."""


def __init__(self, matrix):
self.matrix = matrix

def __str__(self):
"""Вывод матрицы на печать для пользователя."""

return '[' + ']\n['.join('\t'.join(map(str, row)) for row in self.matrix) + ']'


def __repr__(self) -> str:
return '\n' + self.__str__()

def __getitem__(self, index):
return self.matrix[index]

def matrix_size(self):
rows = len(self.matrix)
columns = len(self.matrix[0])
return rows, columns

def get_high(self):
return len(self.matrix[0])

def get_weight(self):
return len(self.matrix)
Comment thread
karmusha marked this conversation as resolved.

def check_matrix_equality(self, other):
"""
Проверяет мартицы одинаковость размерностей
:param self: Первая матрица
:param other: Вторая матрица

:return: True or False
"""

if self.get_high() == other.get_high() and self.get_weight() == other.get_weight():
return True

return False

def __eq__(self, other):
"""Сравнение мартиц одинавовой размерности на равенство"""

if self.check_matrix_equality(other):
res = zip(self.matrix, other)
res = map(lambda x: x[0] == x[1], res)
return all(res)

return False
Comment thread
karmusha marked this conversation as resolved.

def __add__(self, other):
"""Сложение мартиц одинавовой размерности"""

if not self.check_matrix_equality(other):
return 'Нельзя сложить матрицы разных размерностей'
Comment thread
karmusha marked this conversation as resolved.

result = []
numbers = []
for i in range(self.get_weight()):
for j in range(self.get_high()):
summa = other[i][j] + self.matrix[i][j]
numbers.append(summa)
if len(numbers) == len(self.matrix):
result.append(numbers)
numbers = []
Comment thread
karmusha marked this conversation as resolved.

return Matrix(result)

def __mul__(self, other):
"""Умножение мартиц (длина одной матрицы должна быть равна ширине другой матрицы)"""

if self.get_high() != other.get_weight():
return 'Нельзя перемножить такие матрицы'

result = []
for i in range(self.get_weight()):
res = []
for j in range(other.get_weight()):
el, m = 0, 0
for k in range(self.get_high()):
m = self[i][k] * other[k][j]
el += m
res.append(el)
result.append(res)
Comment thread
karmusha marked this conversation as resolved.
return Matrix(result)


if __name__ == '__main__':
m1 = Matrix([
[1, 1, 1],
[2, 2, 2],
[3, 3, 3]
])

m2 = Matrix([
[10, 10, 10],
[20, 20, 20],
[30, 30, 30]
])

m3 = Matrix([
[1, 1, 1],
[2, 2, 2],
[3, 3, 3]
])

print(f'{m1 = }')
print(f'{m2 = }')
print(f'{m3 = }')

print(f'{m1 == m2 = }')
print(f'{m1 == m3 = }')

print(f'{m1 + m2 = }')
print(f'{m1 * m2 = }')
8 changes: 8 additions & 0 deletions new_sem11_oop/pack11/task1.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,15 @@ def __str__(self):
"""Метод представления для пользователя с информацией об авторе, собственно строке и времени ее создания."""

return f'Name: {self.author_name}, string: {self.value}, time: {self.start_time}'

def __repr__(self):
"""Метод представления для разработчика для создания экземпляра из консоли в виде MyString(string, 'author_name')."""

return f'MyString({self.value}, "{self.author_name}")'


s1 = MyString(1, 'Alex')
print(s1)
print(repr(s1))

print(f'Documentation:\n{MyString.__doc__}')