diff --git a/.gitignore b/.gitignore index 022b890..d008c3f 100644 --- a/.gitignore +++ b/.gitignore @@ -129,3 +129,5 @@ dmypy.json # Pyre type checker .pyre/ + +*.DS_Store \ No newline at end of file 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 diff --git a/tasks/practice2/practice2.py b/tasks/practice2/practice2.py index 008f6d1..a5567fe 100644 --- a/tasks/practice2/practice2.py +++ b/tasks/practice2/practice2.py @@ -1,3 +1,5 @@ +import random + from typing import Iterable UNCULTURED_WORDS = ('kotleta', 'pirog') @@ -11,7 +13,7 @@ def greet_user(name: str) -> str: :param name: имя пользователя :return: приветствие """ - + greeting = "Hello, " + name # пиши код здесь return greeting @@ -29,6 +31,7 @@ def get_amount() -> float: """ # пиши код здесь + amount = round(random.randint(10000, 1000000) * random.random(), 2) return amount @@ -41,8 +44,20 @@ def is_phone_correct(phone_number: str) -> bool: :return: буленовское значение - bool: True - если номер корректны, False - если номер некорректный """ + # пиши код здесь + result = True + + if len(phone_number) != 12: + result = False + + if phone_number[:2] != "+7": + result = False + + if not phone_number[2:].isdigit(): + result = False + return result @@ -59,6 +74,7 @@ def is_amount_correct(current_amount: float, transfer_amount: str) -> bool: """ # пиши код здесь + result = float(transfer_amount) <= current_amount return result @@ -78,7 +94,15 @@ def moderate_text(text: str, uncultured_words: Iterable[str]) -> str: """ # пиши код здесь - return result + text = " ".join(text.split()) + text = text.capitalize() + text = text.replace('"', '').replace("'", '') + + for w in uncultured_words: + w_length = len(w) + text = text.replace(w, '#' * w_length) + + return text def create_request_for_loan(user_info: str) -> str: @@ -99,6 +123,10 @@ def create_request_for_loan(user_info: str) -> str: :param user_info: строка с информацией о клиенте :return: текст кредитной заявки """ - + info = user_info.split(',') # пиши код здесь - return result + return (f"Фамилия: {info[0]}\n" + + f"Имя: {info[1]}\n" + + f"Отчество: {info[2]}\n" + + f"Дата рождения: {info[3]}\n" + + f"Запрошенная сумма: {info[4]}") diff --git a/tasks/practice3/practice3.py b/tasks/practice3/practice3.py index 9115c9c..e61a581 100644 --- a/tasks/practice3/practice3.py +++ b/tasks/practice3/practice3.py @@ -1,3 +1,4 @@ +import csv from pathlib import Path from typing import Dict, Any, List, Optional @@ -27,8 +28,19 @@ def count_words(text: str) -> Dict[str, int]: """ # пиши свой код здесь + result = {} + words = text.split() - return {} + for word in words: + if any(char.isdigit() for char in word): + continue + word = ''.join(char.lower() for char in word if char.isalpha()) + if word: + result[word] = result.get(word, 0) + 1 + + return result + + def exp_list(numbers: List[int], exp: int) -> List[int]: @@ -41,8 +53,11 @@ def exp_list(numbers: List[int], exp: int) -> List[int]: """ # пиши свой код здесь + result = [] - return [] + result = [n ** exp for n in numbers] + + return result def get_cashback(operations: List[Dict[str, Any]], special_category: List[str]) -> float: @@ -58,6 +73,15 @@ def get_cashback(operations: List[Dict[str, Any]], special_category: List[str]) :return: размер кешбека """ + + result = 0.0 + + for operation in operations: + if operation['category'] not in special_category: + result += operation['amount'] * 0.01 + else: + result += operation['amount'] * 0.05 + return result @@ -100,5 +124,12 @@ def csv_reader(header: str) -> int: """ # пиши свой код здесь + file_path = get_path_to_file() + result = set() + + with open(file_path, 'r') as file: + reader = csv.DictReader(file) + for row in reader: + result.add(row[header]) - return 0 + return len(result) diff --git a/tasks/practice4/practice4.py b/tasks/practice4/practice4.py index a7d6b8d..64fcc52 100644 --- a/tasks/practice4/practice4.py +++ b/tasks/practice4/practice4.py @@ -40,4 +40,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(): + phone = search_phone(value, name) + if phone is not None: + return phone + + elif isinstance(content, list): + for item in content: + phone = search_phone(item, name) + if phone is not None: + return phone + return None diff --git a/tasks/practice5/employee.py b/tasks/practice5/employee.py index 1d7bad8..328d42f 100644 --- a/tasks/practice5/employee.py +++ b/tasks/practice5/employee.py @@ -37,6 +37,11 @@ def __init__(self, name: str, position: str, salary: int): """ Задача: реализовать конструктор класса, чтобы все тесты проходили """ + if not (isinstance(name, str) and isinstance(position, str) and isinstance(salary, int)): + raise ValueError + self.name = name + self.position = position + self._salary = salary # пиши свой код здесь @@ -44,6 +49,7 @@ def get_salary(self) -> int: """ Метод возвращает зарплату сотрудника. """ + return self._salary # пиши свой код здесь @@ -54,6 +60,16 @@ def __eq__(self, other: object) -> bool: Сравнение происходит по уровню позиции см. `get_position_level`. Если что-то идет не так - бросаются исключения. Смотрим что происходит в тестах. """ + if isinstance(other, Employee): + try: + first_position = get_position_level(self.position) + second_position = get_position_level(other.position) + if first_position == second_position: + return True + return False + except NoSuchPositionError: + raise ValueError + raise TypeError # пиши свой код здесь @@ -62,6 +78,7 @@ def __str__(self): Задача: реализовать строковое представление объекта. Пример вывода: 'name: Ivan position manager' """ + return f'name: {self.name} position: {self.position}' # пиши свой код здесь @@ -81,7 +98,8 @@ def __init__(self, name: str, salary: int, language: str): """ Задача: реализовать конструктор класса, используя конструктор родителя """ - + super().__init__(name, self.position, salary) + self.language = language # пиши свой код здесь @@ -96,5 +114,5 @@ 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..5f6576c 100644 --- a/tasks/practice5/team.py +++ b/tasks/practice5/team.py @@ -26,6 +26,9 @@ def __init__(self, name: str, manager: Manager): Конструктор должен присвоить значения публичным атрибутам и инициализировать контейнер `__members` """ + self.name = name + self.manager = manager + self.__members = set() # пиши свой код здесь @@ -34,6 +37,10 @@ def add_member(self, member: Employee) -> None: Задача: реализовать метод добавления участника в команду. Добавить можно только работника. """ + if isinstance(member, Employee): + self.__members.add(member) + else: + raise TypeError # пиши свой код здесь @@ -42,6 +49,12 @@ def remove_member(self, member: Employee) -> None: Задача: реализовать метод удаления участника из команды. Если в команде нет такого участника поднимается исключение `NoSuchMemberError` """ + if not isinstance(member, Employee): + raise TypeError + if member in self.__members: + self.__members.remove(member) + else: + raise NoSuchMemberError(self.name, member) # пиши свой код здесь @@ -50,9 +63,13 @@ def get_members(self) -> Set[Employee]: Задача: реализовать метод возвращения списка участков команды та, чтобы из вне нельзя было поменять список участников внутри класса """ + return self.__members.copy() # пиши свой код здесь + def __str__(self) -> str: + return f'team: {self.name} manager: {self.manager.name} number of members: {len(self.__members)}' + def show(self) -> None: """ DO NOT EDIT!