Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions tasks/practice1/practice1.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ def concatenate_strings(a: str, b: str) -> str:
:return: результат сложения
"""

# пиши свой код здесь
result = a + b # пиши свой код здесь

return result

Expand All @@ -22,6 +22,6 @@ def calculate_salary(total_compensation: int) -> float:
:return: сумма заплаты после вычета налога
"""

# пиши свой код здесь
result = total_compensation * 0.87 # пиши свой код здесь

return result
53 changes: 42 additions & 11 deletions tasks/practice2/practice2.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ def greet_user(name: str) -> str:
:return: приветствие
"""

# пиши код здесь
greeting = "Guten Tag, " + str.format(name) # пиши код здесь
return greeting


Expand All @@ -28,7 +28,8 @@ def get_amount() -> float:
:return: случайную сумму на счете
"""

# пиши код здесь
import random
amount = float(random.randint(100, 1000000)) # пиши код здесь
return amount


Expand All @@ -42,7 +43,11 @@ def is_phone_correct(phone_number: str) -> bool:
False - если номер некорректный
"""

# пиши код здесь
if phone_number[0:1] == "+" and phone_number[1:].isdigit() and phone_number[1:2] == "7" and len(
phone_number[1:]) == 11:
result = True
else:
result = False
return result


Expand All @@ -58,7 +63,10 @@ def is_amount_correct(current_amount: float, transfer_amount: str) -> bool:
False - если денег недостаточно
"""

# пиши код здесь
if current_amount >= float(transfer_amount): # пиши код здесь
result = True
else:
result = False
return result


Expand All @@ -77,28 +85,51 @@ def moderate_text(text: str, uncultured_words: Iterable[str]) -> str:
:return: текст, соответсвующий правилам
"""

# пиши код здесь
return result
censorship_length = "" # пиши код здесь
for uncultured_word in uncultured_words:
if uncultured_word in text:
for i in range(len(uncultured_word)):
censorship_length = censorship_length + "#"
text = text.replace(uncultured_word, censorship_length)
censorship_length = ""
text = text.casefold()
text = text.split()
text[0] = text[0].title()
text = ' '.join(text)
print(text)
for word in text:
for dangerous_symbol in word:
text = text.replace("'", "")
for word in text:
for dangerous_symbol in word:
text = text.replace('"', '')
text = ' '.join(text.split())
return text


def create_request_for_loan(user_info: str) -> str:
"""
Генерирует заявку на кредит на основе входящей строки.
Формат входящий строки:

Иванов,Петр,Сергеевич,01.01.1991,10000

Что должны вернуть на ее основе:

Фамилия: Иванов
Имя: Петр
Отчество: Сергеевич
Дата рождения: 01.01.1991
Запрошенная сумма: 10000

:param user_info: строка с информацией о клиенте
:return: текст кредитной заявки
"""

# пиши код здесь
intermediate_result = user_info.split(",") # пиши код здесь
result = (("Фамилия: " + intermediate_result[0] + "\n" + "Имя: " + intermediate_result[1] + "\n" + "Отчество: " +
intermediate_result[2]) + "\n" + "Дата рождения: " + intermediate_result[
3] + "\n" + "Запрошенная сумма: "
+ intermediate_result[4])
return result

57 changes: 48 additions & 9 deletions tasks/practice3/practice3.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
from pathlib import Path
from typing import Dict, Any, List, Optional
import csv

import tasks


def count_words(text: str) -> Dict[str, int]:
Expand All @@ -26,9 +29,30 @@ def count_words(text: str) -> Dict[str, int]:
значение - количество вхождений слов в текст
"""

# пиши свой код здесь

return {}
punctuation_symbols = (".", "?", ",", "!", ":", ";", "-", "—")
counter = 0
for i in text:
if i in punctuation_symbols:
text = text.replace(i, "")
text = text.lower().split()
processed_text = ""
dictionary = dict()
for word in range(len(text)):
counter = 0
if any(character.isdigit() for character in text[word]):
counter = 0
else:
counter = counter + 1
if text[word] in processed_text:
counter = counter + 1
else:
processed_text = processed_text + " " + text[word]
if counter > 0:
dictionary[text[word]] = counter
dictionary = sorted(dictionary.items())
dictionary = dict(dictionary)
print(dictionary)
return dictionary


def exp_list(numbers: List[int], exp: int) -> List[int]:
Expand All @@ -40,9 +64,9 @@ def exp_list(numbers: List[int], exp: int) -> List[int]:
:return: список натуральных чисел
"""

# пиши свой код здесь

return []
for i in range(len(numbers)): # пиши свой код здесь
numbers[i] = int(numbers[i]) ** int(exp)
return numbers


def get_cashback(operations: List[Dict[str, Any]], special_category: List[str]) -> float:
Expand All @@ -58,7 +82,15 @@ def get_cashback(operations: List[Dict[str, Any]], special_category: List[str])
:return: размер кешбека
"""

return result
cashback = 0
cat = [i['category'] for i in operations]
am = [i['amount'] for i in operations]
for i in range(len(cat)):
if cat[i] in special_category:
cashback = cashback + 0.05 * float(am[i])
else:
cashback = cashback + 0.01 * float(am[i])
return cashback


def get_path_to_file() -> Optional[Path]:
Expand Down Expand Up @@ -99,6 +131,13 @@ def csv_reader(header: str) -> int:
:return: количество уникальных элементов в столбце
"""

# пиши свой код здесь
file_path = get_path_to_file()
unique_elements = set()
with open(file_path, 'r', newline='') as csvfile:
reader = csv.reader(csvfile)
header_row = next(reader)
column_index = header_row.index(header)
for row in reader:
unique_elements.add(row[column_index])
return len(unique_elements)

return 0
17 changes: 14 additions & 3 deletions tasks/practice4/practice4.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,17 @@ def search_phone(content: Any, name: str) -> Optional[str]:
:return: номер телефона пользователя или None
"""

# пиши свой код здесь

return None
phone_number = None
if isinstance(content, dict):
if 'name' in content and 'phone' in content:
if name == content['name']:
phone_number = content.get('phone')
else:
for potential_dictionary in content.values():
if (isinstance(potential_dictionary, str) is False) and (search_phone(potential_dictionary, name)):
phone_number = search_phone(potential_dictionary, name)
elif isinstance(content, list):
for potential_list in content:
if search_phone(potential_list, name):
phone_number = search_phone(potential_list, name)
return phone_number
25 changes: 19 additions & 6 deletions tasks/practice5/employee.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,14 +38,19 @@ def __init__(self, name: str, position: str, salary: int):
Задача: реализовать конструктор класса, чтобы все тесты проходили
"""

# пиши свой код здесь
if isinstance(name, str) & isinstance(position, str) & isinstance(salary, int): # пиши свой код здесь
self.name = name
self.position = position
self._salary = salary
else:
raise ValueError

def get_salary(self) -> int:
"""
Метод возвращает зарплату сотрудника.
"""

# пиши свой код здесь
return self._salary # пиши свой код здесь

def __eq__(self, other: object) -> bool:
"""
Expand All @@ -55,15 +60,22 @@ 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):
"""
Задача: реализовать строковое представление объекта.
Пример вывода: 'name: Ivan position manager'
"""

# пиши свой код здесь
result = 'name: ' + self.name + ' position: ' + self.position # пиши свой код здесь
return result

def __hash__(self):
return id(self)
Expand All @@ -82,7 +94,8 @@ def __init__(self, name: str, salary: int, language: str):
Задача: реализовать конструктор класса, используя конструктор родителя
"""

# пиши свой код здесь
self.language = language # пиши свой код здесь
super().__init__(name, self.position, salary)


class Manager(Employee):
Expand All @@ -97,4 +110,4 @@ def __init__(self, name: str, salary: int):
Задача: реализовать конструктор класса, используя конструктор родителя
"""

# пиши свой код здесь
super().__init__(name, self.position, salary) # пиши свой код здесь
24 changes: 20 additions & 4 deletions tasks/practice5/team.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,31 +27,42 @@ def __init__(self, name: str, manager: Manager):
и инициализировать контейнер `__members`
"""

# пиши свой код здесь
self.name = name # пиши свой код здесь
self.manager = manager
self.__members = set()

def add_member(self, member: Employee) -> None:
"""
Задача: реализовать метод добавления участника в команду.
Добавить можно только работника.
"""

# пиши свой код здесь
if isinstance(member, Employee): # пиши свой код здесь
self.__members.add(member)
else:
raise NoSuchMemberError

def remove_member(self, member: Employee) -> None:
"""
Задача: реализовать метод удаления участника из команды.
Если в команде нет такого участника поднимается исключение `NoSuchMemberError`
"""

# пиши свой код здесь
if isinstance(member, Employee): # пиши свой код здесь
if member in self.__members:
self.__members.remove(member)
else:
raise NoSuchMemberError(self.name, member)
else:
raise TypeError

def get_members(self) -> Set[Employee]:
"""
Задача: реализовать метод возвращения списка участков команды та,
чтобы из вне нельзя было поменять список участников внутри класса
"""

# пиши свой код здесь
return self.__members.copy() # пиши свой код здесь

def show(self) -> None:
"""
Expand All @@ -65,3 +76,8 @@ def show(self) -> None:
этого метода
"""
print(self)

def __str__(self):
r = "team: " + self.name + " manager: " + self.manager.name
r = r + " number of members: " + str(len(self.get_members()))
return r