From bbeb3ef5bd2db064e8601113df0b94abbd9649f1 Mon Sep 17 00:00:00 2001 From: Crazymax21 Date: Mon, 23 May 2022 12:56:55 +1000 Subject: [PATCH 1/7] =?UTF-8?q?=D0=97=D0=B0=D0=B4=D0=B0=D0=BD=D0=B8=D0=B5?= =?UTF-8?q?=201=20=D1=83=D1=80=D0=BE=D0=BA=D0=B0=20=E2=84=967=20=D0=B2?= =?UTF-8?q?=D1=8B=D0=BF=D0=BE=D0=BB=D0=B5=D0=BD=D0=BD=D0=BE.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .idea/misc.xml | 2 +- .idea/pythoncourse.iml | 2 +- Lesson 7/Task_1.py | 61 ++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 63 insertions(+), 2 deletions(-) create mode 100644 Lesson 7/Task_1.py diff --git a/.idea/misc.xml b/.idea/misc.xml index 0749876..2849f27 100644 --- a/.idea/misc.xml +++ b/.idea/misc.xml @@ -1,6 +1,6 @@ - + diff --git a/.idea/pythoncourse.iml b/.idea/pythoncourse.iml index 8437fe6..f63fa7b 100644 --- a/.idea/pythoncourse.iml +++ b/.idea/pythoncourse.iml @@ -2,7 +2,7 @@ - + \ No newline at end of file diff --git a/Lesson 7/Task_1.py b/Lesson 7/Task_1.py new file mode 100644 index 0000000..395d861 --- /dev/null +++ b/Lesson 7/Task_1.py @@ -0,0 +1,61 @@ +# 1) Реализовать класс Matrix (матрица). Обеспечить перегрузку конструктора класса (метод +# __init__()), который должен принимать данные (список списков) для формирования матрицы. +# Подсказка: матрица — система некоторых математических величин, расположенных в виде +# прямоугольной схемы. +# Примеры матриц: 3 на 2, 3 на 3, 2 на 4. +# 31 22 +# 37 43 +# 51 86 +# 3 5 32 +# 2 4 6 +# -1 64 -8 +# 3 5 8 3 +# 8 3 7 1 +# Следующий шаг — реализовать перегрузку метода __str__() для вывода матрицы в +# привычном виде. +# Далее реализовать перегрузку метода __add__() для реализации операции сложения двух +# объектов класса Matrix (двух матриц). Результатом сложения должна быть новая матрица. +# Подсказка: сложение элементов матриц выполнять поэлементно — первый элемент первой +# строки первой матрицы складываем с первым элементом первой строки второй матрицы и т.д. + +import numpy as np + + +class Matrix: + _sub_matrix = [] + + def __init__(self, user_matrix): + self.sub_matrix = user_matrix + + def __str__(self): + print(*self.sub_matrix, sep='\n') + + def validate_matrix(self, other): + if len(self.sub_matrix) != len(other.sub_matrix): + return False + else: + for i in range(len(self.sub_matrix)): + if len(self.sub_matrix[i]) != len(other.sub_matrix[i]): + return False + return True + + + def __add__(self, other): + if self.validate_matrix(other): + return np.array(self.sub_matrix) + np.array(other.sub_matrix) + else: + return 'Сложить можно только матрицы одного размера' + + +user_list1 = [[1, 2], [3, 4]] +user_list2 = [[5, 6], [7, 8]] + +user_matrix1 = Matrix(user_list1) +user_matrix2 = Matrix(user_list2) + +user_matrix1.__str__() +user_matrix2.__str__() + +user_matrix1.__add__(user_matrix2) + +print(user_matrix1.__add__(user_matrix2)) From 3cb81ef0736114b3d9e96cdd5ec87a99765f80fa Mon Sep 17 00:00:00 2001 From: Crazymax21 Date: Mon, 23 May 2022 13:57:17 +1000 Subject: [PATCH 2/7] =?UTF-8?q?=D0=97=D0=B0=D0=B4=D0=B0=D0=BD=D0=B8=D0=B5?= =?UTF-8?q?=202=20=D1=83=D1=80=D0=BE=D0=BA=D0=B0=20=E2=84=967=20=D0=B2?= =?UTF-8?q?=D1=8B=D0=BF=D0=BE=D0=BB=D0=B5=D0=BD=D0=BD=D0=BE.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Lesson 7/Task 2.py | 70 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 Lesson 7/Task 2.py diff --git a/Lesson 7/Task 2.py b/Lesson 7/Task 2.py new file mode 100644 index 0000000..8d3e62b --- /dev/null +++ b/Lesson 7/Task 2.py @@ -0,0 +1,70 @@ +# 2) Реализовать проект расчета суммарного расхода ткани на производство одежды. Основная +# сущность (класс) этого проекта — одежда, которая может иметь определенное название. К +# типам одежды в этом проекте относятся пальто и костюм. У этих типов одежды существуют +# параметры: размер (для пальто) и рост (для костюма). Это могут быть обычные числа: V и +# H, соответственно. +# Для определения расхода ткани по каждому типу одежды использовать формулы: для пальто +# (V/6.5 + 0.5), для костюма (2*H + 0.3). Проверить работу этих методов на реальных данных. +# Реализовать общий подсчет расхода ткани. Проверить на практике полученные на этом уроке +# знания: реализовать абстрактные классы для основных классов проекта, проверить на +# практике работу декоратора @property +from abc import ABC, abstractmethod + + +class Clothes(ABC): + name = '' + units = [] + + def add_unit(self, unit): + self.units.append(unit) + + @abstractmethod + def requrement(self): + pass + + def __str__(self): + return self.name + + @property + def calc_requrements(self): + total = 0 + for el in self.units: + print(f'Для {el.name} требуется {el.requrement()} ткани') + total += el.requrement() + return f'Всего требуется {total} ткани' + + +class Coat(Clothes): + size = 0 + + def __init__(self, size): + self.name = 'Пальто' + self.size = size + super().add_unit(self) + + def requrement(self): + return self.size / 6.5 + 0.5 + + +class Suit(Clothes): + height = 0 + + def __init__(self, height): + self.name = 'Костюм' + self.height = height + super().add_unit(self) + + def requrement(self): + return 2 * self.height + 0.3 + + +coat1 = Coat(65) +suit1 = Suit(20) + +print(coat1) +print(coat1.requrement()) + +print(suit1) + +print(Clothes.units) +print(coat1.calc_requrements) From bd37a22d1248ac6da6d9420f8d6f950624981a7b Mon Sep 17 00:00:00 2001 From: Crazymax21 Date: Mon, 23 May 2022 15:18:23 +1000 Subject: [PATCH 3/7] =?UTF-8?q?=D0=97=D0=B0=D0=B4=D0=B0=D0=BD=D0=B8=D0=B5?= =?UTF-8?q?=203=20=D1=83=D1=80=D0=BE=D0=BA=D0=B0=20=E2=84=967=20=D0=B2?= =?UTF-8?q?=D1=8B=D0=BF=D0=BE=D0=BB=D0=B5=D0=BD=D0=BD=D0=BE.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Lesson 7/Task 3.py | 95 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 95 insertions(+) create mode 100644 Lesson 7/Task 3.py diff --git a/Lesson 7/Task 3.py b/Lesson 7/Task 3.py new file mode 100644 index 0000000..8fe4278 --- /dev/null +++ b/Lesson 7/Task 3.py @@ -0,0 +1,95 @@ +# 3) Реализовать программу работы с органическими клетками, состоящими из ячеек. Необходимо +# создать класс Клетка. В его конструкторе инициализировать параметр, соответствующий +# количеству ячеек клетки (целое число). В классе должны быть реализованы методы +# © geekbrains.ru 20 +# перегрузки арифметических операторов: сложение (__add__()), вычитание (__sub__()), +# умножение (__mul__()), деление (__truediv__()). Данные методы должны применяться только +# к клеткам и выполнять увеличение, уменьшение, умножение и целочисленное (с округлением +# до целого) деление клеток, соответственно. +# Сложение. Объединение двух клеток. При этом число ячеек общей клетки должно равняться +# сумме ячеек исходных двух клеток. +# Вычитание. Участвуют две клетки. Операцию необходимо выполнять только если разность +# количества ячеек двух клеток больше нуля, иначе выводить соответствующее сообщение. +# Умножение. Создается общая клетка из двух. Число ячеек общей клетки определяется как +# произведение количества ячеек этих двух клеток. +# Деление. Создается общая клетка из двух. Число ячеек общей клетки определяется как +# целочисленное деление количества ячеек этих двух клеток. +# В классе необходимо реализовать метод make_order(), принимающий экземпляр класса и +# количество ячеек в ряду. Данный метод позволяет организовать ячейки по рядам. +# Метод должен возвращать строку вида *****\n*****\n*****..., где количество ячеек между \n +# равно переданному аргументу. Если ячеек на формирование ряда не хватает, то в последний +# ряд записываются все оставшиеся. +# Например, количество ячеек клетки равняется 12, количество ячеек в ряду — 5. Тогда метод +# make_order() вернет строку: *****\n*****\n**. +# Или, количество ячеек клетки равняется 15, количество ячеек в ряду — 5. Тогда метод +# make_order() вернет строку: *****\n*****\n*****. + +class Cell: + + def __init__(self, cells): + self.cells_count = cells + self._cells_row = 7 + self._cell_struct = [] + self._construct_cell() + + def __add__(self, other): + self.cells_count += other.cells_count + self._construct_cell() + + def __sub__(self, other): + if self.cells_count - other.cells_count <= 0: + print('Операция не возможна') + else: + self.cells_count -= other.cells_count + self._construct_cell() + + def __mul__(self, other): + self.cells_count *= other.cells_count + self._construct_cell() + + def __truediv__(self, other): + self.cells_count = self.cells_count // other.cells_count + self._construct_cell() + + def make_order(self, cell_row): + self._cells_row = cell_row + self._construct_cell() + + def _construct_cell(self): + self._cell_struct.clear() + cell_parts = self.cells_count / self._cells_row if self.cells_count % self._cells_row == 0 else ( + self.cells_count // self._cells_row) + 1 + for i in range(int(cell_parts)): + mesh = self._cells_row if self.cells_count - self._cells_row * ( + i) > self._cells_row else self.cells_count - self._cells_row * (i) + self._cell_struct.append(mesh * '*') + + def __str__(self): + print('\n'.join(self._cell_struct)) + + +my_cell1 = Cell(16) + +my_cell2 = Cell(18) + +print('Клетка 1') +my_cell1.__str__() +print('Клетка 2') +my_cell2.__str__() + +# my_cell1.make_order(3) +# +# print('Клетка 1') +# my_cell1.__str__() +# print('Клетка 2') +# my_cell2.__str__() + +# my_cell1.__add__(my_cell2) +# my_cell2.__add__(my_cell1) +my_cell1.__sub__(my_cell2) +#my_cell1.__truediv__(my_cell2) +# my_cell1.__mul__(my_cell2) +print('Клетка 1') +my_cell1.__str__() +print('Клетка 2') +my_cell2.__str__() From a67d03eb763d26f0a7028c1e35747b344ac43666 Mon Sep 17 00:00:00 2001 From: Crazymax21 Date: Mon, 23 May 2022 15:26:40 +1000 Subject: [PATCH 4/7] =?UTF-8?q?=D0=97=D0=B0=D0=B4=D0=B0=D0=BD=D0=B8=D0=B5?= =?UTF-8?q?=203=20=D1=83=D1=80=D0=BE=D0=BA=D0=B0=20=E2=84=967=20=D0=B2?= =?UTF-8?q?=D1=8B=D0=BF=D0=BE=D0=BB=D0=B5=D0=BD=D0=BD=D0=BE.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Lesson 7/Task 3.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Lesson 7/Task 3.py b/Lesson 7/Task 3.py index 8fe4278..cd4820b 100644 --- a/Lesson 7/Task 3.py +++ b/Lesson 7/Task 3.py @@ -26,7 +26,7 @@ class Cell: - def __init__(self, cells): + def __init__(self, cells=0): self.cells_count = cells self._cells_row = 7 self._cell_struct = [] From 4240594c2e9c1d98476e24d056ba800013c1e515 Mon Sep 17 00:00:00 2001 From: Crazymax21 Date: Mon, 23 May 2022 15:33:03 +1000 Subject: [PATCH 5/7] =?UTF-8?q?=D0=9F=D0=BE=D0=BF=D1=80=D0=B0=D0=B2=D0=B8?= =?UTF-8?q?=D0=BB=20=D0=B2=207=20=D0=B7=D0=B0=D0=B4=D0=B0=D0=BD=D0=B8?= =?UTF-8?q?=D0=B8.=20=D0=A1=D0=B4=D0=B5=D0=BB=D0=B0=D0=BB=20=D0=B7=D0=B0?= =?UTF-8?q?=D1=89=D0=B8=D1=89=D0=B5=D0=BD=D1=8B=D0=BC=20=D1=81=D0=B2=D0=BE?= =?UTF-8?q?=D0=B9=D1=81=D1=82=D0=B2=D0=BE=20=5Fcells=5Fcount?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Lesson 7/Task 3.py | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/Lesson 7/Task 3.py b/Lesson 7/Task 3.py index cd4820b..865cc02 100644 --- a/Lesson 7/Task 3.py +++ b/Lesson 7/Task 3.py @@ -27,28 +27,28 @@ class Cell: def __init__(self, cells=0): - self.cells_count = cells + self._cells_count = cells self._cells_row = 7 self._cell_struct = [] self._construct_cell() def __add__(self, other): - self.cells_count += other.cells_count + self._cells_count += other._cells_count self._construct_cell() def __sub__(self, other): - if self.cells_count - other.cells_count <= 0: + if self._cells_count - other._cells_count <= 0: print('Операция не возможна') else: - self.cells_count -= other.cells_count + self._cells_count -= other._cells_count self._construct_cell() def __mul__(self, other): - self.cells_count *= other.cells_count + self._cells_count *= other._cells_count self._construct_cell() def __truediv__(self, other): - self.cells_count = self.cells_count // other.cells_count + self._cells_count = self._cells_count // other._cells_count self._construct_cell() def make_order(self, cell_row): @@ -57,11 +57,11 @@ def make_order(self, cell_row): def _construct_cell(self): self._cell_struct.clear() - cell_parts = self.cells_count / self._cells_row if self.cells_count % self._cells_row == 0 else ( - self.cells_count // self._cells_row) + 1 + cell_parts = self._cells_count / self._cells_row if self._cells_count % self._cells_row == 0 else ( + self._cells_count // self._cells_row) + 1 for i in range(int(cell_parts)): - mesh = self._cells_row if self.cells_count - self._cells_row * ( - i) > self._cells_row else self.cells_count - self._cells_row * (i) + mesh = self._cells_row if self._cells_count - self._cells_row * ( + i) > self._cells_row else self._cells_count - self._cells_row * (i) self._cell_struct.append(mesh * '*') def __str__(self): From 21856dbc519d0e1598c9665fb16746d3b7b99ece Mon Sep 17 00:00:00 2001 From: Crazymax21 Date: Mon, 23 May 2022 17:32:45 +1000 Subject: [PATCH 6/7] =?UTF-8?q?=D0=9F=D0=BE=D0=BF=D1=80=D0=B0=D0=B2=D0=B8?= =?UTF-8?q?=D0=BB=20=D0=B2=207=20=D0=B7=D0=B0=D0=B4=D0=B0=D0=BD=D0=B8?= =?UTF-8?q?=D0=B8.=20=D0=9F=D0=B5=D1=80=D0=B5=D0=BF=D0=B8=D1=81=D0=B0?= =?UTF-8?q?=D0=BB=20=D0=BC=D0=B5=D1=82=D0=BE=D0=B4=D1=8B=20add,=20sub,=20m?= =?UTF-8?q?ul,=20truediv=20=D1=87=D1=82=D0=BE=D0=B1=D1=8B=20=D0=B2=D0=BE?= =?UTF-8?q?=D0=B7=D0=B2=D1=80=D0=B0=D1=89=D0=B0=D0=BB=D0=B8=20=D1=8D=D0=BA?= =?UTF-8?q?=D0=B7=D0=B5=D0=BC=D0=BF=D0=BB=D1=8F=D1=80=20=D0=BD=D0=BE=D0=B2?= =?UTF-8?q?=D0=BE=D0=B9=20=D0=BA=D0=BB=D0=B5=D1=82=D0=BA=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Lesson 7/Task 3.py | 43 +++++++++++++------------------------------ 1 file changed, 13 insertions(+), 30 deletions(-) diff --git a/Lesson 7/Task 3.py b/Lesson 7/Task 3.py index 865cc02..d9a890a 100644 --- a/Lesson 7/Task 3.py +++ b/Lesson 7/Task 3.py @@ -33,23 +33,19 @@ def __init__(self, cells=0): self._construct_cell() def __add__(self, other): - self._cells_count += other._cells_count - self._construct_cell() + return Cell(self._cells_count + other._cells_count) def __sub__(self, other): if self._cells_count - other._cells_count <= 0: - print('Операция не возможна') + return 'Операция не возможна' else: - self._cells_count -= other._cells_count - self._construct_cell() + return Cell(self._cells_count - other._cells_count) def __mul__(self, other): - self._cells_count *= other._cells_count - self._construct_cell() + return Cell(self._cells_count * other._cells_count) def __truediv__(self, other): - self._cells_count = self._cells_count // other._cells_count - self._construct_cell() + return Cell(self._cells_count // other._cells_count) def make_order(self, cell_row): self._cells_row = cell_row @@ -65,31 +61,18 @@ def _construct_cell(self): self._cell_struct.append(mesh * '*') def __str__(self): - print('\n'.join(self._cell_struct)) + return '\n'.join(self._cell_struct) -my_cell1 = Cell(16) +my_cell1 = Cell(7) -my_cell2 = Cell(18) +my_cell2 = Cell(5) print('Клетка 1') -my_cell1.__str__() +print(my_cell1) print('Клетка 2') -my_cell2.__str__() +print(my_cell2) -# my_cell1.make_order(3) -# -# print('Клетка 1') -# my_cell1.__str__() -# print('Клетка 2') -# my_cell2.__str__() - -# my_cell1.__add__(my_cell2) -# my_cell2.__add__(my_cell1) -my_cell1.__sub__(my_cell2) -#my_cell1.__truediv__(my_cell2) -# my_cell1.__mul__(my_cell2) -print('Клетка 1') -my_cell1.__str__() -print('Клетка 2') -my_cell2.__str__() +my_cell3 = my_cell1 / my_cell2 +print('Клетка 3') +print(my_cell3) From 8fb18ca5085dae6ba1ab554470b15164010be32d Mon Sep 17 00:00:00 2001 From: Crazymax21 Date: Mon, 23 May 2022 17:41:12 +1000 Subject: [PATCH 7/7] =?UTF-8?q?=D0=9F=D0=BE=D0=BF=D1=80=D0=B0=D0=B2=D0=B8?= =?UTF-8?q?=D0=BB=20=D0=B2=207=20=D0=B7=D0=B0=D0=B4=D0=B0=D0=BD=D0=B8?= =?UTF-8?q?=D0=B8.=20=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=B8=D0=BB=20=D0=BF?= =?UTF-8?q?=D1=80=D0=BE=D0=B2=D0=B5=D1=80=D0=BA=D1=83=20=D0=B4=D0=B5=D0=BB?= =?UTF-8?q?=D0=B5=D0=BD=D0=B8=D1=8F=20=D0=BD=D0=B0=200?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Lesson 7/Task 3.py | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/Lesson 7/Task 3.py b/Lesson 7/Task 3.py index d9a890a..538a16d 100644 --- a/Lesson 7/Task 3.py +++ b/Lesson 7/Task 3.py @@ -37,7 +37,7 @@ def __add__(self, other): def __sub__(self, other): if self._cells_count - other._cells_count <= 0: - return 'Операция не возможна' + raise TypeError('Операция не возможна') else: return Cell(self._cells_count - other._cells_count) @@ -45,7 +45,10 @@ def __mul__(self, other): return Cell(self._cells_count * other._cells_count) def __truediv__(self, other): - return Cell(self._cells_count // other._cells_count) + if other._cells_count == 0: + raise ZeroDivisionError('Операция не возможна') + else: + return Cell(self._cells_count // other._cells_count) def make_order(self, cell_row): self._cells_row = cell_row @@ -66,7 +69,7 @@ def __str__(self): my_cell1 = Cell(7) -my_cell2 = Cell(5) +my_cell2 = Cell(0) print('Клетка 1') print(my_cell1) @@ -74,5 +77,6 @@ def __str__(self): print(my_cell2) my_cell3 = my_cell1 / my_cell2 +my_cell3.make_order(4) print('Клетка 3') print(my_cell3)