From 6f2fbdd290ceb30169b8cba0a3416769ae270391 Mon Sep 17 00:00:00 2001 From: Ryabchikov Aleksey Andreevich Date: Wed, 19 Jun 2024 18:32:29 +0300 Subject: [PATCH 1/2] Add practice 4 and 5 --- tasks/practice1/practice1.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tasks/practice1/practice1.py b/tasks/practice1/practice1.py index 030da70..21e154a 100644 --- a/tasks/practice1/practice1.py +++ b/tasks/practice1/practice1.py @@ -9,7 +9,7 @@ def concatenate_strings(a: str, b: str) -> str: """ # пиши свой код здесь - + result = a + b return result @@ -23,5 +23,5 @@ def calculate_salary(total_compensation: int) -> float: """ # пиши свой код здесь - + result = total_compensation * 0.87 return result From 1da47a2ed6136687290d3b368675c8707f9fece7 Mon Sep 17 00:00:00 2001 From: nicko587 Date: Wed, 19 Jun 2024 18:36:31 +0300 Subject: [PATCH 2/2] Add practice 4 and 5 --- tasks/practice2/practice2.py | 26 +++++++++++++++++++------- tasks/practice3/practice3.py | 29 +++++++++++++++++++++++------ tasks/practice4/practice4.py | 14 ++++++++++++-- tasks/practice5/employee.py | 24 +++++++++++++++++++++--- tasks/practice5/team.py | 18 +++++++++++++++--- 5 files changed, 90 insertions(+), 21 deletions(-) diff --git a/tasks/practice2/practice2.py b/tasks/practice2/practice2.py index 008f6d1..6280de2 100644 --- a/tasks/practice2/practice2.py +++ b/tasks/practice2/practice2.py @@ -1,3 +1,4 @@ +import random from typing import Iterable 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 = random.randint(10000, 100000000) / 100 return amount @@ -43,6 +46,10 @@ def is_phone_correct(phone_number: str) -> bool: """ # пиши код здесь + if len(phone_number) == 12 and all(i.isdigit() for i in phone_number[2:]) and phone_number[:2] == '+7': + result = True + else: + result = False return result @@ -59,7 +66,7 @@ def is_amount_correct(current_amount: float, transfer_amount: str) -> bool: """ # пиши код здесь - return result + return current_amount >= float(transfer_amount) def moderate_text(text: str, uncultured_words: Iterable[str]) -> str: @@ -76,7 +83,10 @@ def moderate_text(text: str, uncultured_words: Iterable[str]) -> str: :param uncultured_words: список запрещенных слов :return: текст, соответсвующий правилам """ - + result = text.lower().strip() + result = result.replace('"', '').replace("'", '').replace(uncultured_words[0], '#######').replace( + uncultured_words[1], '#####') + result = result[0].upper() + result[1:] # пиши код здесь return result @@ -85,20 +95,22 @@ def create_request_for_loan(user_info: str) -> str: """ Генерирует заявку на кредит на основе входящей строки. Формат входящий строки: - + Иванов,Петр,Сергеевич,01.01.1991,10000 - + Что должны вернуть на ее основе: - + Фамилия: Иванов Имя: Петр Отчество: Сергеевич Дата рождения: 01.01.1991 Запрошенная сумма: 10000 - + :param user_info: строка с информацией о клиенте :return: текст кредитной заявки """ - + data = user_info.split(',') + result = 'Фамилия: ' + data[0] + '\nИмя: ' + data[1] + '\nОтчество: ' + data[2] + '\nДата рождения: ' + data[ + 3] + '\nЗапрошенная сумма: ' + data[4] # пиши код здесь return result diff --git a/tasks/practice3/practice3.py b/tasks/practice3/practice3.py index 9115c9c..ec0a9dd 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 re +import csv def count_words(text: str) -> Dict[str, int]: @@ -27,8 +29,14 @@ def count_words(text: str) -> Dict[str, int]: """ # пиши свой код здесь + result = {} - return {} + mask = r'\b[a-z]+\b' + text = text.lower().strip() + word_list = re.findall(mask, text) + for word in word_list: + result[word] = word_list.count(word) + return result def exp_list(numbers: List[int], exp: int) -> List[int]: @@ -41,8 +49,8 @@ def exp_list(numbers: List[int], exp: int) -> List[int]: """ # пиши свой код здесь - - return [] + result = [i**exp for i in numbers] + return result def get_cashback(operations: List[Dict[str, Any]], special_category: List[str]) -> float: @@ -57,7 +65,12 @@ def get_cashback(operations: List[Dict[str, Any]], special_category: List[str]) :param special_category: список категорий повышенного кешбека :return: размер кешбека """ - + result = 0 + for i in operations: + if i['category'] in special_category: + result += i['amount']*0.05 + else: + result += i['amount']*0.01 return result @@ -100,5 +113,9 @@ def csv_reader(header: str) -> int: """ # пиши свой код здесь - - return 0 + with open(get_path_to_file()) as r_file: + file_reader = csv.DictReader(r_file) + elements = set() + for element in file_reader: + elements.add(element[header]) + return len(elements) diff --git a/tasks/practice4/practice4.py b/tasks/practice4/practice4.py index a7d6b8d..4e66171 100644 --- a/tasks/practice4/practice4.py +++ b/tasks/practice4/practice4.py @@ -39,5 +39,15 @@ def search_phone(content: Any, name: str) -> Optional[str]: """ # пиши свой код здесь - - return None + if isinstance(content, list): + for value in content: + result = search_phone(value, name) + if result != None: + return result + elif isinstance(content, dict): + if name in content.values(): + return content.get('phone') + for value in content.values(): + result = search_phone(value, name) + if result != None: + return result diff --git a/tasks/practice5/employee.py b/tasks/practice5/employee.py index 1d7bad8..13bf719 100644 --- a/tasks/practice5/employee.py +++ b/tasks/practice5/employee.py @@ -12,7 +12,7 @@ def get_position_level(position_name: str) -> int: """ - Функция возвращает уровень позиции по ее названию. + Функция возвращает уровень позиции по ее названию. Если должности нет в базе поднимается исключение `NoSuchPositionError(position_name)` """ try: @@ -37,7 +37,15 @@ def __init__(self, name: str, position: str, salary: int): """ Задача: реализовать конструктор класса, чтобы все тесты проходили """ - + self.name = name + if not isinstance(name, str): + raise ValueError('name must be a string') + self.position = position + if not isinstance(position, str): + raise ValueError('position must be a string') + self._salary = salary + if not isinstance(salary, int): + raise ValueError('salary must be int') # пиши свой код здесь def get_salary(self) -> int: @@ -46,7 +54,7 @@ def get_salary(self) -> int: """ # пиши свой код здесь - + return self._salary def __eq__(self, other: object) -> bool: """ Задача: реализовать метод сравнение двух сотрудников, чтобы все тесты проходили. @@ -56,6 +64,12 @@ def __eq__(self, other: object) -> bool: """ # пиши свой код здесь + if not isinstance(other, Employee): + raise TypeError("Cannot compare Employee with non-Employee object") + try: + return get_position_level(self.position) == get_position_level(other.position) + except NoSuchPositionError: + raise ValueError("Cannot compare Employee objects with undefined positions") def __str__(self): """ @@ -64,6 +78,7 @@ def __str__(self): """ # пиши свой код здесь + return f"name: {self.name} position: {self.position}" def __hash__(self): return id(self) @@ -83,6 +98,8 @@ def __init__(self, name: str, salary: int, language: str): """ # пиши свой код здесь + super().__init__(name, self.position, salary) + self.language = language class Manager(Employee): @@ -98,3 +115,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..1a06663 100644 --- a/tasks/practice5/team.py +++ b/tasks/practice5/team.py @@ -28,7 +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 +38,9 @@ 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,7 +49,11 @@ 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,7 +61,9 @@ def get_members(self) -> Set[Employee]: """ # пиши свой код здесь - + return self.__members.copy() + def __str__(self): + return f'team: {self.name} manager: {self.manager.name} number of members: {len(self.__members)}' def show(self) -> None: """ DO NOT EDIT! @@ -65,3 +76,4 @@ def show(self) -> None: этого метода """ print(self) +