From 0d2319d0e627d5488eefd07c766528db13ddb32f Mon Sep 17 00:00:00 2001 From: Leonie Date: Thu, 18 Apr 2024 04:52:10 +0300 Subject: [PATCH 1/6] 1st and 2d practises have passed all tests successfully. --- tasks/practice1/practice1.py | 4 +-- tasks/practice2/practice2.py | 53 ++++++++++++++++++++++++++++-------- 2 files changed, 44 insertions(+), 13 deletions(-) diff --git a/tasks/practice1/practice1.py b/tasks/practice1/practice1.py index 030da70..a6b738c 100644 --- a/tasks/practice1/practice1.py +++ b/tasks/practice1/practice1.py @@ -8,7 +8,7 @@ def concatenate_strings(a: str, b: str) -> str: :return: результат сложения """ - # пиши свой код здесь + result = a + b # пиши свой код здесь return result @@ -22,6 +22,6 @@ def calculate_salary(total_compensation: int) -> float: :return: сумма заплаты после вычета налога """ - # пиши свой код здесь + result = total_compensation * 0.87 # пиши свой код здесь return result diff --git a/tasks/practice2/practice2.py b/tasks/practice2/practice2.py index 008f6d1..a864396 100644 --- a/tasks/practice2/practice2.py +++ b/tasks/practice2/practice2.py @@ -12,7 +12,7 @@ def greet_user(name: str) -> str: :return: приветствие """ - # пиши код здесь + greeting = "Guten Tag, " + str.format(name) # пиши код здесь return greeting @@ -28,7 +28,8 @@ def get_amount() -> float: :return: случайную сумму на счете """ - # пиши код здесь + import random + amount = float(random.randint(100, 1000000)) # пиши код здесь return amount @@ -42,7 +43,11 @@ def is_phone_correct(phone_number: str) -> bool: False - если номер некорректный """ - # пиши код здесь + if phone_number[0:1] == "+" and phone_number[1:].isdigit() and phone_number[1:2] == "7" and len( + phone_number[1:]) == 11: + result = True + else: + result = False return result @@ -58,7 +63,10 @@ def is_amount_correct(current_amount: float, transfer_amount: str) -> bool: False - если денег недостаточно """ - # пиши код здесь + if current_amount >= float(transfer_amount): # пиши код здесь + result = True + else: + result = False return result @@ -77,28 +85,51 @@ def moderate_text(text: str, uncultured_words: Iterable[str]) -> str: :return: текст, соответсвующий правилам """ - # пиши код здесь - return result + censorship_length = "" # пиши код здесь + for uncultured_word in uncultured_words: + if uncultured_word in text: + for i in range(len(uncultured_word)): + censorship_length = censorship_length + "#" + text = text.replace(uncultured_word, censorship_length) + censorship_length = "" + text = text.casefold() + text = text.split() + text[0] = text[0].title() + text = ' '.join(text) + print(text) + for word in text: + for dangerous_symbol in word: + text = text.replace("'", "") + for word in text: + for dangerous_symbol in word: + text = text.replace('"', '') + text = ' '.join(text.split()) + return text def create_request_for_loan(user_info: str) -> str: """ Генерирует заявку на кредит на основе входящей строки. Формат входящий строки: - + Иванов,Петр,Сергеевич,01.01.1991,10000 - + Что должны вернуть на ее основе: - + Фамилия: Иванов Имя: Петр Отчество: Сергеевич Дата рождения: 01.01.1991 Запрошенная сумма: 10000 - + :param user_info: строка с информацией о клиенте :return: текст кредитной заявки """ - # пиши код здесь + intermediate_result = user_info.split(",") # пиши код здесь + result = (("Фамилия: " + intermediate_result[0] + "\n" + "Имя: " + intermediate_result[1] + "\n" + "Отчество: " + + intermediate_result[2]) + "\n" + "Дата рождения: " + intermediate_result[ + 3] + "\n" + "Запрошенная сумма: " + + intermediate_result[4]) return result + From 3ddb86203d4c59320e30fcfcd96cfe3c88dfc850 Mon Sep 17 00:00:00 2001 From: Leonie Date: Sun, 16 Jun 2024 20:32:35 +0300 Subject: [PATCH 2/6] Practice 3. --- tasks/practice3/practice3.py | 57 ++++++++++++++++++++++++++++++------ 1 file changed, 48 insertions(+), 9 deletions(-) diff --git a/tasks/practice3/practice3.py b/tasks/practice3/practice3.py index 9115c9c..e4ab10b 100644 --- a/tasks/practice3/practice3.py +++ b/tasks/practice3/practice3.py @@ -1,5 +1,8 @@ from pathlib import Path from typing import Dict, Any, List, Optional +import csv + +import tasks def count_words(text: str) -> Dict[str, int]: @@ -26,9 +29,30 @@ def count_words(text: str) -> Dict[str, int]: значение - количество вхождений слов в текст """ - # пиши свой код здесь - - return {} + punctuation_symbols = (".", "?", ",", "!", ":", ";", "-", "—") + counter = 0 + for i in text: + if i in punctuation_symbols: + text = text.replace(i, "") + text = text.lower().split() + processed_text = "" + dictionary = dict() + for word in range(len(text)): + counter = 0 + if any(character.isdigit() for character in text[word]): + counter = 0 + else: + counter = counter + 1 + if text[word] in processed_text: + counter = counter + 1 + else: + processed_text = processed_text + " " + text[word] + if counter > 0: + dictionary[text[word]] = counter + dictionary = sorted(dictionary.items()) + dictionary = dict(dictionary) + print(dictionary) + return dictionary def exp_list(numbers: List[int], exp: int) -> List[int]: @@ -40,9 +64,9 @@ def exp_list(numbers: List[int], exp: int) -> List[int]: :return: список натуральных чисел """ - # пиши свой код здесь - - return [] + for i in range(len(numbers)): # пиши свой код здесь + numbers[i] = int(numbers[i]) ** int(exp) + return numbers def get_cashback(operations: List[Dict[str, Any]], special_category: List[str]) -> float: @@ -58,7 +82,15 @@ def get_cashback(operations: List[Dict[str, Any]], special_category: List[str]) :return: размер кешбека """ - return result + cashback = 0 + cat = [i['category'] for i in operations] + am = [i['amount'] for i in operations] + for i in range(len(cat)): + if cat[i] in special_category: + cashback = cashback + 0.05 * float(am[i]) + else: + cashback = cashback + 0.01 * float(am[i]) + return cashback def get_path_to_file() -> Optional[Path]: @@ -99,6 +131,13 @@ def csv_reader(header: str) -> int: :return: количество уникальных элементов в столбце """ - # пиши свой код здесь + file_path = get_path_to_file() + unique_elements = set() + with open(file_path, 'r', newline='') as csvfile: + reader = csv.reader(csvfile) + header_row = next(reader) + column_index = header_row.index(header) + for row in reader: + unique_elements.add(row[column_index]) + return len(unique_elements) - return 0 From 6826abd3abe36b917f6fa34c49f3e318a69849a5 Mon Sep 17 00:00:00 2001 From: Leonie Date: Sun, 16 Jun 2024 20:32:53 +0300 Subject: [PATCH 3/6] Practice 4. --- tasks/practice4/practice4.py | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/tasks/practice4/practice4.py b/tasks/practice4/practice4.py index a7d6b8d..e320d35 100644 --- a/tasks/practice4/practice4.py +++ b/tasks/practice4/practice4.py @@ -38,6 +38,17 @@ def search_phone(content: Any, name: str) -> Optional[str]: :return: номер телефона пользователя или None """ - # пиши свой код здесь - - return None + phone_number = None + if isinstance(content, dict): + if 'name' in content and 'phone' in content: + if name == content['name']: + phone_number = content.get('phone') + else: + for potential_dictionary in content.values(): + if (isinstance(potential_dictionary, str) is False) and (search_phone(potential_dictionary, name)): + phone_number = search_phone(potential_dictionary, name) + elif isinstance(content, list): + for potential_list in content: + if search_phone(potential_list, name): + phone_number = search_phone(potential_list, name) + return phone_number \ No newline at end of file From 66eb8e56e39a4faa25d4f5656ebcc292b76ebe0d Mon Sep 17 00:00:00 2001 From: Leonie Date: Sun, 16 Jun 2024 20:33:35 +0300 Subject: [PATCH 4/6] Practice 5. --- tasks/practice5/employee.py | 25 +++++++++++++++++++------ tasks/practice5/team.py | 24 ++++++++++++++++++++---- 2 files changed, 39 insertions(+), 10 deletions(-) diff --git a/tasks/practice5/employee.py b/tasks/practice5/employee.py index 1d7bad8..7bc17bc 100644 --- a/tasks/practice5/employee.py +++ b/tasks/practice5/employee.py @@ -38,14 +38,19 @@ def __init__(self, name: str, position: str, salary: int): Задача: реализовать конструктор класса, чтобы все тесты проходили """ - # пиши свой код здесь + if isinstance(name, str) & isinstance(position, str) & isinstance(salary, int): # пиши свой код здесь + self.name = name + self.position = position + self._salary = salary + else: + raise ValueError def get_salary(self) -> int: """ Метод возвращает зарплату сотрудника. """ - # пиши свой код здесь + return self._salary # пиши свой код здесь def __eq__(self, other: object) -> bool: """ @@ -55,7 +60,13 @@ def __eq__(self, other: object) -> bool: Если что-то идет не так - бросаются исключения. Смотрим что происходит в тестах. """ - # пиши свой код здесь + if isinstance(other, Employee): # пиши свой код здесь + try: + return get_position_level(self.position) == get_position_level(other.position) + except NoSuchPositionError: + raise ValueError + else: + raise TypeError def __str__(self): """ @@ -63,7 +74,8 @@ def __str__(self): Пример вывода: 'name: Ivan position manager' """ - # пиши свой код здесь + result = 'name: ' + self.name + ' position: ' + self.position # пиши свой код здесь + return result def __hash__(self): return id(self) @@ -82,7 +94,8 @@ def __init__(self, name: str, salary: int, language: str): Задача: реализовать конструктор класса, используя конструктор родителя """ - # пиши свой код здесь + self.language = language # пиши свой код здесь + super().__init__(name, self.position, salary) class Manager(Employee): @@ -97,4 +110,4 @@ def __init__(self, name: str, salary: int): Задача: реализовать конструктор класса, используя конструктор родителя """ - # пиши свой код здесь + super().__init__(name, self.position, salary) # пиши свой код здесь diff --git a/tasks/practice5/team.py b/tasks/practice5/team.py index 934796c..d8b888f 100644 --- a/tasks/practice5/team.py +++ b/tasks/practice5/team.py @@ -27,7 +27,9 @@ def __init__(self, name: str, manager: Manager): и инициализировать контейнер `__members` """ - # пиши свой код здесь + self.name = name # пиши свой код здесь + self.manager = manager + self.__members = set() def add_member(self, member: Employee) -> None: """ @@ -35,7 +37,10 @@ def add_member(self, member: Employee) -> None: Добавить можно только работника. """ - # пиши свой код здесь + if isinstance(member, Employee): # пиши свой код здесь + self.__members.add(member) + else: + raise NoSuchMemberError def remove_member(self, member: Employee) -> None: """ @@ -43,7 +48,13 @@ def remove_member(self, member: Employee) -> None: Если в команде нет такого участника поднимается исключение `NoSuchMemberError` """ - # пиши свой код здесь + if isinstance(member, Employee): # пиши свой код здесь + if member in self.__members: + self.__members.remove(member) + else: + raise NoSuchMemberError(self.name, member) + else: + raise TypeError def get_members(self) -> Set[Employee]: """ @@ -51,7 +62,7 @@ def get_members(self) -> Set[Employee]: чтобы из вне нельзя было поменять список участников внутри класса """ - # пиши свой код здесь + return self.__members.copy() # пиши свой код здесь def show(self) -> None: """ @@ -65,3 +76,8 @@ def show(self) -> None: этого метода """ print(self) + + def __str__(self): + r = "team: " + self.name + " manager: " + self.manager.name + r = r + " number of members: " + str(len(self.get_members())) + return r From b47fa8c24ccffb2e5e88842cfd4dc77621c9b79b Mon Sep 17 00:00:00 2001 From: Leonie Date: Sun, 16 Jun 2024 21:28:05 +0300 Subject: [PATCH 5/6] 1st commit --- tasks/practice1/practice1.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tasks/practice1/practice1.py b/tasks/practice1/practice1.py index a6b738c..4eb81fc 100644 --- a/tasks/practice1/practice1.py +++ b/tasks/practice1/practice1.py @@ -10,7 +10,7 @@ def concatenate_strings(a: str, b: str) -> str: result = a + b # пиши свой код здесь - return result + return result def calculate_salary(total_compensation: int) -> float: From 857a6cd43761b3fefdb3c6296e667d9afdcb40da Mon Sep 17 00:00:00 2001 From: Leonie Date: Sun, 16 Jun 2024 21:33:20 +0300 Subject: [PATCH 6/6] 1st practice --- tasks/practice1/practice1.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tasks/practice1/practice1.py b/tasks/practice1/practice1.py index 4eb81fc..a6b738c 100644 --- a/tasks/practice1/practice1.py +++ b/tasks/practice1/practice1.py @@ -10,7 +10,7 @@ def concatenate_strings(a: str, b: str) -> str: result = a + b # пиши свой код здесь - return result + return result def calculate_salary(total_compensation: int) -> float: