From ec7b2bd4f37cb5fb4f024c13b9f45d6797a2f3a5 Mon Sep 17 00:00:00 2001 From: Oleg Frolov Date: Sun, 16 Jun 2024 21:55:49 +0300 Subject: [PATCH] =?UTF-8?q?=D0=A1=D0=BE=D1=85=D1=80=D0=B0=D0=BD=D0=B5?= =?UTF-8?q?=D0=BD=D0=B8=D0=B5=20=D0=BF=D0=B5=D1=80=D0=B5=D0=B4=20rebase?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tasks/practice1/practice1.py | 10 ++++++---- tasks/practice2/practice2.py | 32 ++++++++++++++++++++++++++++---- tasks/practice3/practice3.py | 34 ++++++++++++++++++++++++++++++---- tasks/practice4/practice4.py | 13 +++++++++++++ tasks/practice5/employee.py | 22 ++++++++++++++++++++++ tasks/practice5/team.py | 24 ++++++++++++++++++++++++ 6 files changed, 123 insertions(+), 12 deletions(-) diff --git a/tasks/practice1/practice1.py b/tasks/practice1/practice1.py index 030da70..0cd6df9 100644 --- a/tasks/practice1/practice1.py +++ b/tasks/practice1/practice1.py @@ -2,26 +2,28 @@ def concatenate_strings(a: str, b: str) -> str: """ Функция для сложения двух строк. Результат сложения запишите в переменную result. - :param a: число :param b: число :return: результат сложения """ # пиши свой код здесь - - return result + result = a + b + return result def calculate_salary(total_compensation: int) -> float: """ Функция расчета зарплаты, которую сотрудник получит после вычета налогов. Ставка налогообложения равна 13%. - :param total_compensation: сумма зарплаты до вычета налога :return: сумма заплаты после вычета налога """ # пиши свой код здесь + tax_rate = 0.13 + tax_amount = total_compensation * tax_rate + result = total_compensation - tax_amount return result +# pytest tests/test_practice5.py \ No newline at end of file diff --git a/tasks/practice2/practice2.py b/tasks/practice2/practice2.py index 008f6d1..e0cf50a 100644 --- a/tasks/practice2/practice2.py +++ b/tasks/practice2/practice2.py @@ -1,4 +1,5 @@ from typing import Iterable +import random UNCULTURED_WORDS = ('kotleta', 'pirog') @@ -13,6 +14,7 @@ def greet_user(name: str) -> str: """ # пиши код здесь + greeting = f"Привет, {name}! Добро пожаловать в наш бот." return greeting @@ -29,6 +31,7 @@ def get_amount() -> float: """ # пиши код здесь + amount = round(random.uniform(100, 1000000), 2) return amount @@ -43,7 +46,9 @@ def is_phone_correct(phone_number: str) -> bool: """ # пиши код здесь - return result + if len(phone_number) == 12 and phone_number.startswith('+7') and phone_number[2:].isdigit(): + return True + return False def is_amount_correct(current_amount: float, transfer_amount: str) -> bool: @@ -59,7 +64,13 @@ def is_amount_correct(current_amount: float, transfer_amount: str) -> bool: """ # пиши код здесь - return result + try: + transfer_amount_float = float(transfer_amount) + if current_amount >= transfer_amount_float: + return True + except ValueError: + pass + return False def moderate_text(text: str, uncultured_words: Iterable[str]) -> str: @@ -78,7 +89,11 @@ def moderate_text(text: str, uncultured_words: Iterable[str]) -> str: """ # пиши код здесь - return result + text = text.strip().capitalize() + text = text.replace('"', '').replace("'", "") + for word in uncultured_words: + text = text.replace(word, '#' * len(word)) + return text def create_request_for_loan(user_info: str) -> str: @@ -101,4 +116,13 @@ def create_request_for_loan(user_info: str) -> str: """ # пиши код здесь - return result + try: + last_name, first_name, middle_name, birth_date, loan_amount = user_info.split(',') + result = (f"Фамилия: {last_name}\n" + f"Имя: {first_name}\n" + f"Отчество: {middle_name}\n" + f"Дата рождения: {birth_date}\n" + f"Запрошенная сумма: {loan_amount}") + return result + except ValueError: + raise ValueError diff --git a/tasks/practice3/practice3.py b/tasks/practice3/practice3.py index 9115c9c..55e8a6e 100644 --- a/tasks/practice3/practice3.py +++ b/tasks/practice3/practice3.py @@ -1,5 +1,7 @@ from pathlib import Path from typing import Dict, Any, List, Optional +import csv +import re def count_words(text: str) -> Dict[str, int]: @@ -27,8 +29,18 @@ def count_words(text: str) -> Dict[str, int]: """ # пиши свой код здесь + words = re.findall(r'\b[a-zA-Z]{2,}\b', text) + words_count = {} - return {} + for word in words: + word = word.lower() + if not any(char.isdigit() for char in word): + if word in words_count: + words_count[word] += 1 + else: + words_count[word] = 1 + + return words_count def exp_list(numbers: List[int], exp: int) -> List[int]: @@ -42,7 +54,7 @@ def exp_list(numbers: List[int], exp: int) -> List[int]: # пиши свой код здесь - return [] + return [number ** exp for number in numbers] def get_cashback(operations: List[Dict[str, Any]], special_category: List[str]) -> float: @@ -58,6 +70,14 @@ def get_cashback(operations: List[Dict[str, Any]], special_category: List[str]) :return: размер кешбека """ + result = 0.0 + for operation in operations: + amount = operation['amount'] + category = operation['category'] + if category in special_category: + result += amount * 0.05 + else: + result += amount * 0.01 return result @@ -100,5 +120,11 @@ def csv_reader(header: str) -> int: """ # пиши свой код здесь - - return 0 + path_to_file = get_path_to_file() + with path_to_file.open(newline='') as csvfile: + reader = csv.DictReader(csvfile) + unique_elements = set() + for row in reader: + unique_elements.add(row[header]) + + return len(unique_elements) diff --git a/tasks/practice4/practice4.py b/tasks/practice4/practice4.py index a7d6b8d..fcf9f3c 100644 --- a/tasks/practice4/practice4.py +++ b/tasks/practice4/practice4.py @@ -39,5 +39,18 @@ def search_phone(content: Any, name: str) -> Optional[str]: """ # пиши свой код здесь + if isinstance(content, dict): + if content.get('name') == name: + return content.get('phone') + for value in content.values(): + result = search_phone(value, name) + if result: + return result + + elif isinstance(content, list): + for item in content: + result = search_phone(item, name) + if result: + return result return None diff --git a/tasks/practice5/employee.py b/tasks/practice5/employee.py index 1d7bad8..e7cb085 100644 --- a/tasks/practice5/employee.py +++ b/tasks/practice5/employee.py @@ -39,6 +39,17 @@ def __init__(self, name: str, position: str, salary: int): """ # пиши свой код здесь + if not isinstance(salary, int): + raise ValueError("Salary must be an integer") + + self.name = name + self.position = position + self._salary = salary + + try: + self.position_level = get_position_level(self.position) + except NoSuchPositionError: + self.position_level = -1 def get_salary(self) -> int: """ @@ -46,6 +57,7 @@ def get_salary(self) -> int: """ # пиши свой код здесь + return self._salary def __eq__(self, other: object) -> bool: """ @@ -56,6 +68,12 @@ def __eq__(self, other: object) -> bool: """ # пиши свой код здесь + if not isinstance(other, Employee): + raise TypeError("Comparison only possible between Employee instances") + try: + return get_position_level(self.position) == get_position_level(other.position) + except NoSuchPositionError: + raise ValueError("Invalid position for comparison") def __str__(self): """ @@ -64,6 +82,7 @@ def __str__(self): """ # пиши свой код здесь + return f'name: {self.name} position: {self.position}' def __hash__(self): return id(self) @@ -83,6 +102,8 @@ def __init__(self, name: str, salary: int, language: str): """ # пиши свой код здесь + super().__init__(name, self.position, salary) + self.language = language class Manager(Employee): @@ -98,3 +119,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..6f6206a 100644 --- a/tasks/practice5/team.py +++ b/tasks/practice5/team.py @@ -28,6 +28,9 @@ def __init__(self, name: str, manager: Manager): """ # пиши свой код здесь + self.name = name + self.manager = manager + self.__members = set() def add_member(self, member: Employee) -> None: """ @@ -36,6 +39,10 @@ def add_member(self, member: Employee) -> None: """ # пиши свой код здесь + if not isinstance(member, Employee): + raise TypeError("Only instances of Employee can be added to the team") + + self.__members.add(member) def remove_member(self, member: Employee) -> None: """ @@ -44,6 +51,13 @@ def remove_member(self, member: Employee) -> None: """ # пиши свой код здесь + if not isinstance(member, Employee): + raise TypeError("Only instances of Employee can be removed from the team") + + if member not in self.__members: + raise NoSuchMemberError(self.name, member) + + self.__members.remove(member) def get_members(self) -> Set[Employee]: """ @@ -52,6 +66,16 @@ def get_members(self) -> Set[Employee]: """ # пиши свой код здесь + try: + return self.__members.copy() + except Exception as e: + print(f"Error getting members: {e}") + + def __str__(self): + """ + Задача: реализовать строковое представление объекта. + """ + return f'team: {self.name} manager: {self.manager.name} number of members: {len(self.__members)}' def show(self) -> None: """