From 99769bd8ef8e3d3e33a07c34262e8c50c087d983 Mon Sep 17 00:00:00 2001 From: Crazymax21 Date: Tue, 24 May 2022 11:44:14 +1000 Subject: [PATCH 1/8] =?UTF-8?q?=D0=A3=D1=80=D0=BE=D0=BA=20=E2=84=968.=20?= =?UTF-8?q?=D0=97=D0=B0=D0=B4=D0=B0=D0=BD=D0=B8=D0=B5=20=E2=84=961.=20?= =?UTF-8?q?=D0=92=D1=8B=D0=BF=D0=BE=D0=BB=D0=BD=D0=B5=D0=BD=D0=BE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .idea/pythoncourse.iml | 4 +++- Lesson 8/Task 1.py | 42 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 45 insertions(+), 1 deletion(-) create mode 100644 Lesson 8/Task 1.py diff --git a/.idea/pythoncourse.iml b/.idea/pythoncourse.iml index f63fa7b..8542c87 100644 --- a/.idea/pythoncourse.iml +++ b/.idea/pythoncourse.iml @@ -1,7 +1,9 @@ - + + + diff --git a/Lesson 8/Task 1.py b/Lesson 8/Task 1.py new file mode 100644 index 0000000..4f2e43b --- /dev/null +++ b/Lesson 8/Task 1.py @@ -0,0 +1,42 @@ +# 1. Реализовать класс «Дата», функция-конструктор которого должна принимать дату в виде +# строки формата «день-месяц-год». В рамках класса реализовать два метода. Первый, с +# декоратором @classmethod. Он должен извлекать число, месяц, год и преобразовывать их тип +# к типу «Число». Второй, с декоратором @staticmethod, должен проводить валидацию числа, +# месяца и года (например, месяц — от 1 до 12). Проверить работу полученной структуры на +# реальных данных. + +class Date: + _day = 0 + _month = 0 + _year = 0 + + def __init__(self, date_str): + self.extract_date(date_str) + + @classmethod + def extract_date(cls, date_str=''): + date_list = list(map(int, date_str.split('-'))) + if cls.validate(date_list[1], date_list[2]): + cls._day = date_list[0] + cls._month = date_list[1] + cls._year = date_list[2] + + @staticmethod + def validate(month, year): + if 1 <= month <= 12: + if 1900 <= year <= 3000: + return True + else: + raise TypeError('Год не попадает в промежуток от 1900 до 3000') + else: + raise TypeError('Месяц не попадает в промежуток от 1 до 12') + + def __str__(self): + return f'{self._day}/{self._month}/{self._year}' + + +date_str = '01-13-2000' + +my_date = Date(date_str) + +print(my_date) \ No newline at end of file From eec9ac3aa27075e9b28c1e0d06616663a3241cff Mon Sep 17 00:00:00 2001 From: Crazymax21 Date: Tue, 24 May 2022 12:23:04 +1000 Subject: [PATCH 2/8] =?UTF-8?q?=D0=A3=D1=80=D0=BE=D0=BA=20=E2=84=968.=20?= =?UTF-8?q?=D0=97=D0=B0=D0=B4=D0=B0=D0=BD=D0=B8=D0=B5=20=E2=84=962=20?= =?UTF-8?q?=D0=B2=D1=8B=D0=BF=D0=BE=D0=BB=D0=BD=D0=B5=D0=BD=D0=BE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Lesson 8/Task_2.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 Lesson 8/Task_2.py diff --git a/Lesson 8/Task_2.py b/Lesson 8/Task_2.py new file mode 100644 index 0000000..93b5a18 --- /dev/null +++ b/Lesson 8/Task_2.py @@ -0,0 +1,17 @@ +# 2. Создайте собственный класс-исключение, обрабатывающий ситуацию деления на ноль. +# Проверьте его работу на данных, вводимых пользователем. При вводе нуля в качестве +# делителя программа должна корректно обработать эту ситуацию и не завершиться с ошибкой. + +class MyError(Exception): + def __init__(self, txt): + self.txt = txt + + def __str__(self): + return self.txt + + +input_data = input("Введите выражение: ") + +input_data = list(map(float, input_data.split('/'))) +result = input_data[0]/input_data[1] if input_data[1] != 0 else MyError('На 0 делить нельзя') +print(result) From 2ca33f2417b2250a65891db7dff1a6569cfe6e58 Mon Sep 17 00:00:00 2001 From: Crazymax21 Date: Tue, 24 May 2022 12:28:41 +1000 Subject: [PATCH 3/8] =?UTF-8?q?=D0=A3=D1=80=D0=BE=D0=BA=20=E2=84=968.=20?= =?UTF-8?q?=D0=97=D0=B0=D0=B4=D0=B0=D0=BD=D0=B8=D0=B5=20=E2=84=962=20?= =?UTF-8?q?=D0=B2=D1=8B=D0=BF=D0=BE=D0=BB=D0=BD=D0=B5=D0=BD=D0=BE.=20?= =?UTF-8?q?=D0=9F=D0=B5=D1=80=D0=B5=D0=BF=D0=B8=D1=81=D0=B0=D0=BB=20=D0=BD?= =?UTF-8?q?=D0=B0=20=D0=B1=D0=BE=D0=BB=D0=B5=D0=B5=20=D0=BF=D1=80=D0=B0?= =?UTF-8?q?=D0=B2=D0=B8=D0=BB=D1=8C=D0=BD=D1=8B=D0=B9=20=D0=B2=D0=B0=D1=80?= =?UTF-8?q?=D0=B8=D0=B0=D0=BD=D1=82.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Lesson 8/Task_2.py | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/Lesson 8/Task_2.py b/Lesson 8/Task_2.py index 93b5a18..b0f3700 100644 --- a/Lesson 8/Task_2.py +++ b/Lesson 8/Task_2.py @@ -13,5 +13,11 @@ def __str__(self): input_data = input("Введите выражение: ") input_data = list(map(float, input_data.split('/'))) -result = input_data[0]/input_data[1] if input_data[1] != 0 else MyError('На 0 делить нельзя') -print(result) +try: + if input_data[1] == 0: + raise MyError('На 0 делить нельзя') + result = input_data[0] / input_data[1] + print(result) +except MyError as err: + print(err) + From 909fd82bb18dc9fbffa0bfbd812607f22ceb4834 Mon Sep 17 00:00:00 2001 From: Crazymax21 Date: Tue, 24 May 2022 13:01:40 +1000 Subject: [PATCH 4/8] =?UTF-8?q?=D0=A3=D1=80=D0=BE=D0=BA=20=E2=84=968.=20?= =?UTF-8?q?=D0=97=D0=B0=D0=B4=D0=B0=D0=BD=D0=B8=D0=B5=20=E2=84=963=20?= =?UTF-8?q?=D0=B2=D1=8B=D0=BF=D0=BE=D0=BB=D0=BD=D0=B5=D0=BD=D0=BE.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Lesson 8/Task_3.py | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 Lesson 8/Task_3.py diff --git a/Lesson 8/Task_3.py b/Lesson 8/Task_3.py new file mode 100644 index 0000000..dcd1fba --- /dev/null +++ b/Lesson 8/Task_3.py @@ -0,0 +1,37 @@ +# 3. Создайте собственный класс-исключение, который должен проверять содержимое списка на +# наличие только чисел. Проверить работу исключения на реальном примере. Запрашивать у +# пользователя данные и заполнять список необходимо только числами. Класс-исключение +# должен контролировать типы данных элементов списка. +# Примечание: длина списка не фиксирована. Элементы запрашиваются бесконечно, пока +# пользователь сам не остановит работу скрипта, введя, например, команду «stop». При этом +# скрипт завершается, сформированный список с числами выводится на экран. +# Подсказка: для этого задания примем, что пользователь может вводить только числа и строки. +# Во время ввода пользователем очередного элемента необходимо реализовать проверку типа +# элемента. Вносить его в список, только если введено число. Класс-исключение должен не +# позволить пользователю ввести текст (не число) и отобразить соответствующее сообщение. +# При этом работа скрипта не должна завершаться. + +class ValidString(Exception): + + def __init__(self, txt): + self.txt = txt + + def __str__(self): + return self.txt + +user_list = [] + +while True: + user_string = input('Введите число: ') + if user_string == '': + print('Ввод окончен') + break + try: + if not user_string.replace('.', '').isdigit(): + raise ValidString('Вы ввели не число') + user_list.append(int(user_string) if '.' not in user_string else float(user_string)) + except ValidString as err: + print(err) + +print(user_list) + From b33b69a7c104dcd38c095795c2eedae2e92c8e3e Mon Sep 17 00:00:00 2001 From: Crazymax21 Date: Tue, 24 May 2022 14:31:07 +1000 Subject: [PATCH 5/8] =?UTF-8?q?=D0=A3=D1=80=D0=BE=D0=BA=20=E2=84=968.=20?= =?UTF-8?q?=D0=97=D0=B0=D0=B4=D0=B0=D0=BD=D0=B8=D0=B5=20=E2=84=964-5-6=20?= =?UTF-8?q?=D0=B2=D1=8B=D0=BF=D0=BE=D0=BB=D0=BD=D0=B5=D0=BD=D0=BE.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Lesson 8/Task_4.py | 125 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 125 insertions(+) create mode 100644 Lesson 8/Task_4.py diff --git a/Lesson 8/Task_4.py b/Lesson 8/Task_4.py new file mode 100644 index 0000000..9009af8 --- /dev/null +++ b/Lesson 8/Task_4.py @@ -0,0 +1,125 @@ +# 4. Начните работу над проектом «Склад оргтехники». Создайте класс, описывающий склад. А +# также класс «Оргтехника», который будет базовым для классов-наследников. Эти классы — +# конкретные типы оргтехники (принтер, сканер, ксерокс). В базовом классе определите +# параметры, общие для приведённых типов. В классах-наследниках реализуйте параметры, +# уникальные для каждого типа оргтехники. + +class IsExist(Exception): + + def __init__(self, txt): + self.txt = txt + + def __str__(self): + return self.txt + +class Store: + def __init__(self): + self.equipments = {} + + def add_equipment(self, place, equipment): + if place in self.equipments.keys() and self.equipments[place] == equipment: + print('Оборудование уже находится на этом месте') + return False + elif self.get_values(self.equipments, equipment): + print(f'Это оборудование уже лежит на складе. Место {self.get_values(self.equipments, equipment)}') + return False + elif place in self.equipments.keys() and self.equipments[place] != equipment: + print(f'На месте {place} лежит {self.equipments[place]}') + return False + else: + self.equipments[place] = equipment + print('Оборудование добавлено на склад') + return True + + def __str__(self): + for i, el in self.equipments.items(): + print(f'{i}: {el}') + return '' + + def remove_equipment(self, equipment): + if self.get_values(self.equipments, equipment): + self.equipments.pop(self.get_values(self.equipments, equipment)) + print(f'Оборудование {equipment} убрано со склада') + return True + else: + print('Такого оборудования нет') + return False + + def get_equipment(self, place): + try: + if place not in self.equipments.keys(): + raise IsExist('Такого места не существует') + return self.equipments[place] + except IsExist as err: + return err + + @staticmethod + def get_values(my_dict={}, element=''): + for i, el in my_dict.items(): + if element == el: + return i + return False + + +class Office_Equipments: + + def __init__(self, type_equipment, cost_equipment): + self.type_equipment = type_equipment + self.cost_equipment = cost_equipment + + +class Printers(Office_Equipments): + + def __init__(self, cost, name): + super().__init__('Принтер', cost) + self.name = name + + def __str__(self): + return (f'{self.name} {self.type_equipment} {self.cost_equipment}') + + +class Scanners(Office_Equipments): + + def __init__(self, cost, name): + super().__init__('Сканнер', cost) + self.name = name + + def __str__(self): + return (f'{self.name} {self.type_equipment} {self.cost_equipment}') + + +class CopyMachines(Office_Equipments): + + def __init__(self, cost, name): + super().__init__('МФУ', cost) + self.name = name + + def __str__(self): + return (f'{self.name} {self.type_equipment} {self.cost_equipment}') + +my_printer = Printers(10000, 'Для бухгалтерии') +my_scanner = Scanners(15000, 'Для рекламщиков') +my_copymachine = CopyMachines(20000, 'В цех') +my_printer2 = Printers(10000, 'Для ИТ') + +print('Выводим оборудование') +print(my_printer) +print(my_scanner) +print(my_copymachine) + +my_store = Store() + +my_store.add_equipment(1, my_printer) +my_store.add_equipment(2, my_scanner) +my_store.add_equipment(3, my_copymachine) +my_store.add_equipment(1, my_printer2) +print('Выводим склад после добавления') +print(my_store) + + +my_store.remove_equipment(my_scanner) + +print('Выводим склад после удаления') +print(my_store) + +print(my_store.get_equipment(0)) From 68345419af72482eb22061bdb9f7ef672c1dd262 Mon Sep 17 00:00:00 2001 From: Crazymax21 Date: Tue, 24 May 2022 14:53:28 +1000 Subject: [PATCH 6/8] =?UTF-8?q?=D0=A3=D1=80=D0=BE=D0=BA=20=E2=84=968.=20?= =?UTF-8?q?=D0=97=D0=B0=D0=B4=D0=B0=D0=BD=D0=B8=D0=B5=20=E2=84=967=20?= =?UTF-8?q?=D0=B2=D1=8B=D0=BF=D0=BE=D0=BB=D0=BD=D0=B5=D0=BD=D0=BE.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Lesson 8/Task_7.py | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 Lesson 8/Task_7.py diff --git a/Lesson 8/Task_7.py b/Lesson 8/Task_7.py new file mode 100644 index 0000000..f7cbcb9 --- /dev/null +++ b/Lesson 8/Task_7.py @@ -0,0 +1,38 @@ +# 7. Реализовать проект «Операции с комплексными числами». Создайте класс «Комплексное +# число». Реализуйте перегрузку методов сложения и умножения комплексных чисел. Проверьте +# работу проекта. Для этого создаёте экземпляры класса (комплексные числа), выполните +# сложение и умножение созданных экземпляров. Проверьте корректность полученного +# результата. + +class Complex: + + def __init__(self, digit=''): + self.a = int(digit.split('+')[0]) + self.b = int(digit.split('+')[1].replace('i','')) + + def __str__(self): + return f'{self.a}+{self.b}i' + + def __add__(self, other): + a = self.a + other.a + b = self.b + other.b + return Complex(f'{a}+{b}i') + + def __mul__(self, other): + a = self.a * other.a - self.b * other.b + b = self.b * other.a + self.a * other.b + return Complex(f'{a}+{b}i') + + +my_first_digit = Complex('30+6i') +my_second_digit = Complex('3+10i') + +print(my_first_digit) +print(my_second_digit) + +my_third_digit = my_first_digit + my_second_digit + +print(my_third_digit) + +my_fourth_digit = my_first_digit * my_second_digit +print(my_fourth_digit) From be1da457eddbc41c165cafd8b0c52f827f3ba718 Mon Sep 17 00:00:00 2001 From: Crazymax21 Date: Tue, 24 May 2022 14:59:49 +1000 Subject: [PATCH 7/8] =?UTF-8?q?=D0=A3=D1=80=D0=BE=D0=BA=20=E2=84=968.=20?= =?UTF-8?q?=D0=97=D0=B0=D0=B4=D0=B0=D0=BD=D0=B8=D0=B5=207=20=D0=BF=D0=B5?= =?UTF-8?q?=D1=80=D0=B5=D0=BF=D0=B8=D1=81=D0=B0=D0=BB=20=D0=BD=D0=B0=20?= =?UTF-8?q?=D0=BF=D0=B0=D1=80=D0=B0=D0=BC=D0=B5=D1=82=D1=80=D1=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Lesson 8/Task_7.py | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/Lesson 8/Task_7.py b/Lesson 8/Task_7.py index f7cbcb9..7a3566b 100644 --- a/Lesson 8/Task_7.py +++ b/Lesson 8/Task_7.py @@ -6,26 +6,25 @@ class Complex: - def __init__(self, digit=''): - self.a = int(digit.split('+')[0]) - self.b = int(digit.split('+')[1].replace('i','')) + def __init__(self, a, b): + self.a = int(a) + self.b = int(b) def __str__(self): - return f'{self.a}+{self.b}i' - + return f'{self.a}+{self.b}i' if self.b >= 0 else f'{self.a}{self.b}i' def __add__(self, other): a = self.a + other.a b = self.b + other.b - return Complex(f'{a}+{b}i') + return Complex(a, b) def __mul__(self, other): a = self.a * other.a - self.b * other.b b = self.b * other.a + self.a * other.b - return Complex(f'{a}+{b}i') + return Complex(a, b) -my_first_digit = Complex('30+6i') -my_second_digit = Complex('3+10i') +my_first_digit = Complex(30, -2) +my_second_digit = Complex(6, 10) print(my_first_digit) print(my_second_digit) From d67fe51f5cfbc098232d0e2f731d81a0b4230468 Mon Sep 17 00:00:00 2001 From: Crazymax21 Date: Tue, 24 May 2022 15:00:48 +1000 Subject: [PATCH 8/8] =?UTF-8?q?=D0=A3=D1=80=D0=BE=D0=BA=20=E2=84=968.=20?= =?UTF-8?q?=D0=97=D0=B0=D0=B4=D0=B0=D0=BD=D0=B8=D0=B5=207.=20=D0=9F=D0=BE?= =?UTF-8?q?=D0=BF=D1=80=D0=B0=D0=B2=D0=B8=D0=BB=20=D0=BE=D1=84=D0=BE=D1=80?= =?UTF-8?q?=D0=BC=D0=BB=D0=B5=D0=BD=D0=B8=D0=B5.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Lesson 8/Task_7.py | 1 + 1 file changed, 1 insertion(+) diff --git a/Lesson 8/Task_7.py b/Lesson 8/Task_7.py index 7a3566b..7f495ba 100644 --- a/Lesson 8/Task_7.py +++ b/Lesson 8/Task_7.py @@ -12,6 +12,7 @@ def __init__(self, a, b): def __str__(self): return f'{self.a}+{self.b}i' if self.b >= 0 else f'{self.a}{self.b}i' + def __add__(self, other): a = self.a + other.a b = self.b + other.b