From 7fee1eecbdfc631613db9cab071ff8d93676bbd2 Mon Sep 17 00:00:00 2001 From: anton7up <99725170+anton7up@users.noreply.github.com> Date: Sun, 16 Jun 2024 19:38:48 +0300 Subject: [PATCH 1/9] Update practice1.py --- tasks/practice1/practice1.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tasks/practice1/practice1.py b/tasks/practice1/practice1.py index 030da70..d49a1f3 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 - (total_compensation*0.13) + return result From a512c92966db9b02c8c675c4686d759190b58007 Mon Sep 17 00:00:00 2001 From: anton7up <99725170+anton7up@users.noreply.github.com> Date: Sun, 16 Jun 2024 19:41:56 +0300 Subject: [PATCH 2/9] Update practice2.py --- tasks/practice2/practice2.py | 30 +++++++++++++++++++++--------- 1 file changed, 21 insertions(+), 9 deletions(-) diff --git a/tasks/practice2/practice2.py b/tasks/practice2/practice2.py index 008f6d1..a8e74a0 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 = 'Hello, ' + name + '!' return greeting @@ -27,8 +28,8 @@ 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[:2] == '+7') and (phone_number[2:].isdigit()) 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,8 +78,12 @@ def moderate_text(text: str, uncultured_words: Iterable[str]) -> str: :return: текст, соответсвующий правилам """ - # пиши код здесь - return result + text = text.strip().capitalize() + text = ' '.join(text.split()) + text = text.replace('"', '').replace("'", '') + for word in uncultured_words: + text = text.replace(word.lower(), '#' * len(word)) + return text def create_request_for_loan(user_info: str) -> str: @@ -100,5 +105,12 @@ def create_request_for_loan(user_info: str) -> str: :return: текст кредитной заявки """ - # пиши код здесь - return result + user_info = user_info.split(',') + formatted_text = ( + f"Фамилия: {user_info[0]}\n" + f"Имя: {user_info[1]}\n" + f"Отчество: {user_info[2]}\n" + f"Дата рождения: {user_info[3]}\n" + f"Запрошенная сумма: {user_info[4]}" + ) + return formatted_text From 6418b5597d38561beef0c1c35d104a5df1f0cda5 Mon Sep 17 00:00:00 2001 From: anton7up <99725170+anton7up@users.noreply.github.com> Date: Sun, 16 Jun 2024 19:45:57 +0300 Subject: [PATCH 3/9] Update practice3.py --- tasks/practice3/practice3.py | 37 ++++++++++++++++++++++++++++-------- 1 file changed, 29 insertions(+), 8 deletions(-) diff --git a/tasks/practice3/practice3.py b/tasks/practice3/practice3.py index 9115c9c..64d2530 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,15 @@ def count_words(text: str) -> Dict[str, int]: значение - количество вхождений слов в текст """ - # пиши свой код здесь - - return {} + words = text.split() + result = {} + 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]: @@ -40,9 +47,10 @@ def exp_list(numbers: List[int], exp: int) -> List[int]: :return: список натуральных чисел """ - # пиши свой код здесь - - return [] + result = [] + for number in numbers: + result.append(number ** exp) + return result def get_cashback(operations: List[Dict[str, Any]], special_category: List[str]) -> float: @@ -58,6 +66,12 @@ def get_cashback(operations: List[Dict[str, Any]], special_category: List[str]) :return: размер кешбека """ + result = 0 + for operation in operations: + if operation['category'] in special_category: + result += operation['amount'] * 0.05 + else: + result += operation['amount'] * 0.01 return result @@ -99,6 +113,13 @@ def csv_reader(header: str) -> int: :return: количество уникальных элементов в столбце """ - # пиши свой код здесь + file_path = get_path_to_file() + with open(file_path, newline='', encoding='utf-8') as csvfile: + reader = csv.DictReader(csvfile) + unique_values = set() + + for row in reader: + if header in row: + unique_values.add(row[header]) - return 0 + return len(unique_values) From c23115632c34b49ec0c0270bbcb9bc9460eba428 Mon Sep 17 00:00:00 2001 From: anton7up <99725170+anton7up@users.noreply.github.com> Date: Sun, 16 Jun 2024 19:48:40 +0300 Subject: [PATCH 4/9] Update practice4.py --- tasks/practice4/practice4.py | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/tasks/practice4/practice4.py b/tasks/practice4/practice4.py index a7d6b8d..cd453db 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') == name: + return content.get('phone') + for value in content.values(): + result = search_phone(value, name) + if result is not None: + return result + elif isinstance(content, list): + for item in content: + result = search_phone(item, name) + if result is not None: + return result return None From 59a14f53434fd226b9134deb13fa35432f97e558 Mon Sep 17 00:00:00 2001 From: anton7up <99725170+anton7up@users.noreply.github.com> Date: Sun, 16 Jun 2024 19:50:49 +0300 Subject: [PATCH 5/9] Update employee.py --- tasks/practice5/employee.py | 22 ++++++++++++++++------ 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/tasks/practice5/employee.py b/tasks/practice5/employee.py index 1d7bad8..7ec1300 100644 --- a/tasks/practice5/employee.py +++ b/tasks/practice5/employee.py @@ -38,14 +38,18 @@ def __init__(self, name: str, position: str, salary: int): Задача: реализовать конструктор класса, чтобы все тесты проходили """ - # пиши свой код здесь + if 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 +59,12 @@ def __eq__(self, other: object) -> bool: Если что-то идет не так - бросаются исключения. Смотрим что происходит в тестах. """ - # пиши свой код здесь + if not isinstance(other, Employee): + raise TypeError + try: + return get_position_level(self.position) == get_position_level(other.position) + except NoSuchPositionError: + raise ValueError def __str__(self): """ @@ -63,7 +72,7 @@ def __str__(self): Пример вывода: 'name: Ivan position manager' """ - # пиши свой код здесь + return f"name: {self.name} position: {self.position}" def __hash__(self): return id(self) @@ -82,7 +91,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, Manager.position, salary) From 3e04618012b933310018f743a5092b96a30957ab Mon Sep 17 00:00:00 2001 From: anton7up <99725170+anton7up@users.noreply.github.com> Date: Sun, 16 Jun 2024 19:52:15 +0300 Subject: [PATCH 6/9] Update team.py --- tasks/practice5/team.py | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/tasks/practice5/team.py b/tasks/practice5/team.py index 934796c..fa78448 100644 --- a/tasks/practice5/team.py +++ b/tasks/practice5/team.py @@ -19,6 +19,9 @@ class Team: manager: Manager __members: Set[Employee] + def __str__(self): + return f'team: {self.name} manager: {self.manager.name} number of members: {len(self.__members)}' + def __init__(self, name: str, manager: Manager): """ Задача: @@ -27,7 +30,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 +40,9 @@ def add_member(self, member: Employee) -> None: Добавить можно только работника. """ - # пиши свой код здесь + if not isinstance(member, Employee): + raise TypeError + self.__members.add(member) def remove_member(self, member: Employee) -> None: """ @@ -43,7 +50,11 @@ def remove_member(self, member: Employee) -> None: Если в команде нет такого участника поднимается исключение `NoSuchMemberError` """ - # пиши свой код здесь + if not isinstance(member, Employee): + raise TypeError + if member not in self.__members: + raise NoSuchMemberError(member.name, member) + self.__members.remove(member) def get_members(self) -> Set[Employee]: """ @@ -51,7 +62,7 @@ def get_members(self) -> Set[Employee]: чтобы из вне нельзя было поменять список участников внутри класса """ - # пиши свой код здесь + return set(self.__members) def show(self) -> None: """ From 0d6a216d023947db50da9abe8084508c8b116409 Mon Sep 17 00:00:00 2001 From: anton7up <99725170+anton7up@users.noreply.github.com> Date: Mon, 17 Jun 2024 17:33:59 +0300 Subject: [PATCH 7/9] Update practice2.py --- tasks/practice2/practice2.py | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/tasks/practice2/practice2.py b/tasks/practice2/practice2.py index a8e74a0..680a349 100644 --- a/tasks/practice2/practice2.py +++ b/tasks/practice2/practice2.py @@ -13,7 +13,7 @@ def greet_user(name: str) -> str: :return: приветствие """ - greeting = 'Hello, ' + name + '!' + greeting = 'Hi, ' + name return greeting @@ -29,8 +29,7 @@ def get_amount() -> float: :return: случайную сумму на счете """ - amount = round(random.uniform(100, 1000000), 2) - return amount + return round(random.uniform(100, 1000000), 2) def is_phone_correct(phone_number: str) -> bool: @@ -43,8 +42,7 @@ def is_phone_correct(phone_number: str) -> bool: False - если номер некорректный """ - result = (phone_number[:2] == '+7') and (phone_number[2:].isdigit()) - return result + return (phone_number[:2] == '+7') and (phone_number[2:].isdigit()) def is_amount_correct(current_amount: float, transfer_amount: str) -> bool: @@ -59,8 +57,7 @@ def is_amount_correct(current_amount: float, transfer_amount: str) -> bool: False - если денег недостаточно """ - result = current_amount >= float(transfer_amount) - return result + return current_amount >= float(transfer_amount) def moderate_text(text: str, uncultured_words: Iterable[str]) -> str: From 14dbb1165b5b04d20abb1325e4dc1f7519547c20 Mon Sep 17 00:00:00 2001 From: anton7up <99725170+anton7up@users.noreply.github.com> Date: Mon, 17 Jun 2024 17:34:56 +0300 Subject: [PATCH 8/9] Update practice3.py --- tasks/practice3/practice3.py | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/tasks/practice3/practice3.py b/tasks/practice3/practice3.py index 64d2530..d1797fe 100644 --- a/tasks/practice3/practice3.py +++ b/tasks/practice3/practice3.py @@ -27,15 +27,19 @@ def count_words(text: str) -> Dict[str, int]: значение - количество вхождений слов в текст """ + punctuation_marks = ",.?!:;-" + for mark in punctuation_marks: + text = text.replace(mark, "") words = text.split() - result = {} - 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 + valid_words = [word.lower().strip() for word in words if word.isalpha()] + word_count = {} + for word in valid_words: + if word in word_count: + word_count[word] += 1 + else: + word_count[word] = 1 + + return word_count def exp_list(numbers: List[int], exp: int) -> List[int]: From a2fdb43407a95fc667ae113cbc84b768795bb35e Mon Sep 17 00:00:00 2001 From: anton7up <99725170+anton7up@users.noreply.github.com> Date: Mon, 17 Jun 2024 17:35:19 +0300 Subject: [PATCH 9/9] Update practice4.py --- tasks/practice4/practice4.py | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/tasks/practice4/practice4.py b/tasks/practice4/practice4.py index cd453db..caeb2d1 100644 --- a/tasks/practice4/practice4.py +++ b/tasks/practice4/practice4.py @@ -42,12 +42,14 @@ def search_phone(content: Any, name: str) -> Optional[str]: if content.get('name') == name: return content.get('phone') for value in content.values(): - result = search_phone(value, name) - if result is not None: - return result + phone = search_phone(value, name) + if phone is not None: + return phone + elif isinstance(content, list): for item in content: - result = search_phone(item, name) - if result is not None: - return result + phone = search_phone(item, name) + if phone is not None: + return phone + return None