diff --git a/tasks/practice1/practice1.py b/tasks/practice1/practice1.py index 030da70..365b23f 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/bot.py b/tasks/practice2/bot.py index 54c6692..4535f7b 100644 --- a/tasks/practice2/bot.py +++ b/tasks/practice2/bot.py @@ -36,7 +36,7 @@ 'get_loan': get_loan_state, } -BOT_TOKEN = os.environ['BOT_TOKEN'] +BOT_TOKEN = os.environ['---'] def start(update: Update, context: CallbackContext) -> None: diff --git a/tasks/practice2/practice2.py b/tasks/practice2/practice2.py index 008f6d1..30bc676 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') @@ -12,7 +13,7 @@ def greet_user(name: str) -> str: :return: приветствие """ - # пиши код здесь + greeting = f'Hello, my friend {name}!' return greeting @@ -28,7 +29,7 @@ def get_amount() -> float: :return: случайную сумму на счете """ - # пиши код здесь + amount = round(random.uniform(100, 1000000), 2) return amount @@ -42,7 +43,7 @@ def is_phone_correct(phone_number: str) -> bool: False - если номер некорректный """ - # пиши код здесь + result = phone_number[0:2] == "+7" and phone_number[2:].isdigit() and len(phone_number) == 12 return result @@ -58,7 +59,7 @@ def is_amount_correct(current_amount: float, transfer_amount: str) -> bool: False - если денег недостаточно """ - # пиши код здесь + result = current_amount >= float(transfer_amount) return result @@ -77,7 +78,11 @@ def moderate_text(text: str, uncultured_words: Iterable[str]) -> str: :return: текст, соответсвующий правилам """ - # пиши код здесь + result = ''.join(filter(lambda sym: sym not in ['"', "'"], text)) + for i in uncultured_words: + result = result.replace(i, len(i) * '#') + result = result.strip() + result = result[0].upper() + result[1:].lower() return result @@ -85,20 +90,25 @@ def create_request_for_loan(user_info: str) -> str: """ Генерирует заявку на кредит на основе входящей строки. Формат входящий строки: - + Иванов,Петр,Сергеевич,01.01.1991,10000 - + Что должны вернуть на ее основе: - + Фамилия: Иванов Имя: Петр Отчество: Сергеевич Дата рождения: 01.01.1991 Запрошенная сумма: 10000 - + :param user_info: строка с информацией о клиенте :return: текст кредитной заявки """ - # пиши код здесь - return result + result = "" + list_user_info = user_info.split(',') + dictionary = {'Фамилия': list_user_info[0], 'Имя': list_user_info[1], 'Отчество': list_user_info[2], + 'Дата рождения': list_user_info[3], 'Запрошенная сумма': list_user_info[4]} + for i in dictionary: + result += f'{i}: {dictionary[i]}\n' + return result.rstrip('\n') diff --git a/tasks/practice3/practice3.py b/tasks/practice3/practice3.py index 9115c9c..3c4f7aa 100644 --- a/tasks/practice3/practice3.py +++ b/tasks/practice3/practice3.py @@ -1,5 +1,6 @@ from pathlib import Path from typing import Dict, Any, List, Optional +import csv def count_words(text: str) -> Dict[str, int]: @@ -26,9 +27,22 @@ def count_words(text: str) -> Dict[str, int]: значение - количество вхождений слов в текст """ - # пиши свой код здесь + text = text.lower() + punctuation_marks = [',', '.', '?', '!', ':', ';', '-'] + text_without_marks = "" + for i in range(len(text)): + if text[i] in punctuation_marks: + continue + text_without_marks += text[i] + words = text_without_marks.split() - return {} + dictionary = {} + for item in words: + if len(item) > 1 and item.isalpha(): + if item not in dictionary: + dictionary[item] = 0 + dictionary[item] += 1 + return dictionary def exp_list(numbers: List[int], exp: int) -> List[int]: @@ -40,9 +54,9 @@ def exp_list(numbers: List[int], exp: int) -> List[int]: :return: список натуральных чисел """ - # пиши свой код здесь + result = [i**exp for i in numbers] - return [] + return result def get_cashback(operations: List[Dict[str, Any]], special_category: List[str]) -> float: @@ -58,6 +72,12 @@ def get_cashback(operations: List[Dict[str, Any]], special_category: List[str]) :return: размер кешбека """ + result = 0 + for purchase in operations: + if purchase['category'] in special_category: + result += purchase['amount'] * 0.05 + else: + result += purchase['amount'] * 0.01 return result @@ -99,6 +119,15 @@ def csv_reader(header: str) -> int: :return: количество уникальных элементов в столбце """ - # пиши свой код здесь - - return 0 + PATH = get_path_to_file() + s = set() + with open(PATH, 'r') as f: + reader = csv.reader(f) + headers = next(reader) + i = headers.index(header) + + for row in reader: + if row[i] not in s: + s.add(row[i]) + result = len(s) + return result diff --git a/tasks/practice4/practice4.py b/tasks/practice4/practice4.py index a7d6b8d..0bbfe81 100644 --- a/tasks/practice4/practice4.py +++ b/tasks/practice4/practice4.py @@ -38,6 +38,16 @@ def search_phone(content: Any, name: str) -> Optional[str]: :return: номер телефона пользователя или None """ - # пиши свой код здесь - + if isinstance(content, dict): + if content.get('name') and content['name'] == name: + return content['phone'] + for key, value in content.items(): + result = search_phone(value, name) + if result: + return result + if isinstance(content, list): + for elem in content: + result = search_phone(elem, name) + if result: + return result return None diff --git a/tasks/practice5/employee.py b/tasks/practice5/employee.py index 1d7bad8..0810984 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 not isinstance(name, str) or not isinstance(position, str) or not isinstance(salary, int): + raise ValueError + + self.name = name + self.position = position + self._salary = salary 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,12 +74,11 @@ def __str__(self): Пример вывода: 'name: Ivan position manager' """ - # пиши свой код здесь + return f'name: {self.name} position: {self.position}' def __hash__(self): return id(self) - class Developer(Employee): """ Сотрудник - разработчик @@ -82,8 +92,8 @@ def __init__(self, name: str, salary: int, language: str): Задача: реализовать конструктор класса, используя конструктор родителя """ - # пиши свой код здесь - + super().__init__(name, self.position, salary) + self.language = language class Manager(Employee): """ @@ -97,4 +107,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..543b8db 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 TypeError def remove_member(self, member: Employee) -> None: """ @@ -43,7 +48,13 @@ def remove_member(self, member: Employee) -> None: Если в команде нет такого участника поднимается исключение `NoSuchMemberError` """ - # пиши свой код здесь + if isinstance(member, Employee): + try: + self.__members.remove(member) + except: + 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,6 @@ def show(self) -> None: этого метода """ print(self) + + def __str__(self) -> str: + return f'team: {self.name} manager: {self.manager.name} number of members: {len(self.__members)}' \ No newline at end of file