diff --git a/.vs/ProjectSettings.json b/.vs/ProjectSettings.json new file mode 100644 index 0000000..f8b4888 --- /dev/null +++ b/.vs/ProjectSettings.json @@ -0,0 +1,3 @@ +{ + "CurrentProjectSetting": null +} \ No newline at end of file diff --git a/.vs/PythonSettings.json b/.vs/PythonSettings.json new file mode 100644 index 0000000..d99c9fb --- /dev/null +++ b/.vs/PythonSettings.json @@ -0,0 +1,3 @@ +{ + "SuppressConfigureTestFrameworkPrompt": "true" +} \ No newline at end of file diff --git a/.vs/VSWorkspaceState.json b/.vs/VSWorkspaceState.json new file mode 100644 index 0000000..364354e --- /dev/null +++ b/.vs/VSWorkspaceState.json @@ -0,0 +1,7 @@ +{ + "ExpandedNodes": [ + "" + ], + "SelectedNode": "\\C:\\Users\\Denis\\Source\\Repos\\hse-python-2024", + "PreviewInSolutionExplorer": false +} \ No newline at end of file diff --git a/.vs/hse-python-2024/v17/.wsuo b/.vs/hse-python-2024/v17/.wsuo new file mode 100644 index 0000000..69d7ee3 Binary files /dev/null and b/.vs/hse-python-2024/v17/.wsuo differ diff --git a/.vs/hse-python-2024/v17/DocumentLayout.json b/.vs/hse-python-2024/v17/DocumentLayout.json new file mode 100644 index 0000000..43b68aa --- /dev/null +++ b/.vs/hse-python-2024/v17/DocumentLayout.json @@ -0,0 +1,27 @@ +{ + "Version": 1, + "WorkspaceRootPath": "C:\\Users\\Denis\\source\\repos\\hse-python-2024\\", + "Documents": [], + "DocumentGroupContainers": [ + { + "Orientation": 1, + "VerticalTabListWidth": 256, + "DocumentGroups": [ + { + "DockedHeight": 265, + "SelectedChildIndex": -1, + "Children": [ + { + "$type": "Bookmark", + "Name": "ST:128:0:{116d2292-e37d-41cd-a077-ebacac4c8cc4}" + }, + { + "$type": "Bookmark", + "Name": "ST:1:0:{e8b06f52-6d01-11d2-aa7d-00c04f990343}" + } + ] + } + ] + } + ] +} \ No newline at end of file diff --git a/.vs/slnx.sqlite b/.vs/slnx.sqlite new file mode 100644 index 0000000..ef6d8df Binary files /dev/null and b/.vs/slnx.sqlite differ diff --git a/tasks/practice1/practice1.py b/tasks/practice1/practice1.py index 030da70..2d109c0 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,7 @@ def calculate_salary(total_compensation: int) -> float: """ # пиши свой код здесь + tax = 0.13 + result = total_compensation * (1 - tax) return result diff --git a/tasks/practice2/practice2.py b/tasks/practice2/practice2.py index 008f6d1..230e765 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 = "Hello " + name return greeting @@ -29,6 +31,7 @@ def get_amount() -> float: """ # пиши код здесь + amount = round(random.uniform(100, 1000000), 2) return amount @@ -43,6 +46,12 @@ def is_phone_correct(phone_number: str) -> bool: """ # пиши код здесь + result = False + if phone_number[0] == '+': + if phone_number[1] == '7': + if len(phone_number) == 12: + if phone_number[1:].isdigit(): + result = True return result @@ -59,6 +68,9 @@ def is_amount_correct(current_amount: float, transfer_amount: str) -> bool: """ # пиши код здесь + result = True + if float(transfer_amount) > current_amount: + result = False return result @@ -78,6 +90,14 @@ def moderate_text(text: str, uncultured_words: Iterable[str]) -> str: """ # пиши код здесь + a = text + a = ' '.join(a.split()) + a = a.capitalize() + a = a.replace("'", "") + a = a.replace('"', '') + a = a.replace('kotleta', '#######') + a = a.replace('pirog', '#####') + result = a return result @@ -101,4 +121,6 @@ def create_request_for_loan(user_info: str) -> str: """ # пиши код здесь + 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..e7c2015 100644 --- a/tasks/practice3/practice3.py +++ b/tasks/practice3/practice3.py @@ -1,6 +1,9 @@ from pathlib import Path from typing import Dict, Any, List, Optional +import csv + +PUNCTUATION_MARKS = ['.', ',', ';', '?', '!', '-', ':', '"', '\'', '(', ')'] def count_words(text: str) -> Dict[str, int]: """ @@ -27,8 +30,18 @@ def count_words(text: str) -> Dict[str, int]: """ # пиши свой код здесь + text = text.lower() + for mark in PUNCTUATION_MARKS: + if mark in text: + text = text.replace(mark, '') + words = text.split() + dictionary = {} + for word in words: + if dictionary.get(word) == None and word.isalpha(): + dictionary[word] = words.count(word) + + return dictionary - return {} def exp_list(numbers: List[int], exp: int) -> List[int]: @@ -41,8 +54,9 @@ def exp_list(numbers: List[int], exp: int) -> List[int]: """ # пиши свой код здесь + result = [number ** exp for number in numbers] - return [] + return result def get_cashback(operations: List[Dict[str, Any]], special_category: List[str]) -> float: @@ -58,6 +72,14 @@ 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 @@ -100,5 +122,16 @@ def csv_reader(header: str) -> int: """ # пиши свой код здесь - - return 0 + column = [] + with open(get_path_to_file()) as file: + csv_file = csv.DictReader(file) + for row in csv_file: + column.append(row[header]) + + unique_elements = [] + for element in column: + if element not in unique_elements: + unique_elements.append(element) + + return len(unique_elements) + diff --git a/tasks/practice4/practice4.py b/tasks/practice4/practice4.py index a7d6b8d..f31d00d 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 is not 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 is not None: + return result \ No newline at end of file diff --git a/tasks/practice5/employee.py b/tasks/practice5/employee.py index 1d7bad8..fdfeb62 100644 --- a/tasks/practice5/employee.py +++ b/tasks/practice5/employee.py @@ -37,14 +37,22 @@ 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: """ Метод возвращает зарплату сотрудника. """ - + return self._salary # пиши свой код здесь def __eq__(self, other: object) -> bool: @@ -54,7 +62,12 @@ def __eq__(self, other: object) -> bool: Сравнение происходит по уровню позиции см. `get_position_level`. Если что-то идет не так - бросаются исключения. Смотрим что происходит в тестах. """ - + 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): @@ -62,7 +75,7 @@ def __str__(self): Задача: реализовать строковое представление объекта. Пример вывода: 'name: Ivan position manager' """ - + return f'name: {self.name} position: {self.position}' # пиши свой код здесь def __hash__(self): @@ -81,7 +94,8 @@ def __init__(self, name: str, salary: int, language: str): """ Задача: реализовать конструктор класса, используя конструктор родителя """ - + super().__init__(name, self.position, salary) + self.language = language # пиши свой код здесь @@ -96,5 +110,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..ecfd545 100644 --- a/tasks/practice5/team.py +++ b/tasks/practice5/team.py @@ -26,7 +26,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: @@ -34,7 +36,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: @@ -42,7 +46,11 @@ def remove_member(self, member: Employee) -> None: Задача: реализовать метод удаления участника из команды. Если в команде нет такого участника поднимается исключение `NoSuchMemberError` """ - + 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]: @@ -50,7 +58,10 @@ 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: