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
6 changes: 3 additions & 3 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 - (total_compensation*0.13)
return result
33 changes: 21 additions & 12 deletions tasks/practice2/practice2.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from typing import Iterable
import random

UNCULTURED_WORDS = ('kotleta', 'pirog')

Expand All @@ -12,7 +13,7 @@ def greet_user(name: str) -> str:
:return: приветствие
"""

# пиши код здесь
greeting = 'Hi, ' + name
return greeting


Expand All @@ -27,9 +28,8 @@ def get_amount() -> float:

:return: случайную сумму на счете
"""

# пиши код здесь
return amount

return round(random.uniform(100, 1000000), 2)


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

# пиши код здесь
return result
return (phone_number[:2] == '+7') and (phone_number[2:].isdigit())


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

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


def moderate_text(text: str, uncultured_words: Iterable[str]) -> str:
Expand All @@ -77,8 +75,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:
Expand All @@ -100,5 +102,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
41 changes: 33 additions & 8 deletions tasks/practice3/practice3.py
Original file line number Diff line number Diff line change
@@ -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]:
Expand All @@ -26,9 +27,19 @@ def count_words(text: str) -> Dict[str, int]:
значение - количество вхождений слов в текст
"""

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

return {}
punctuation_marks = ",.?!:;-"
for mark in punctuation_marks:
text = text.replace(mark, "")
words = text.split()
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]:
Expand All @@ -40,9 +51,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:
Expand All @@ -58,6 +70,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


Expand Down Expand Up @@ -99,6 +117,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)
14 changes: 13 additions & 1 deletion tasks/practice4/practice4.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,18 @@ 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():
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
22 changes: 16 additions & 6 deletions tasks/practice5/employee.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
"""
Expand All @@ -55,15 +59,20 @@ 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):
"""
Задача: реализовать строковое представление объекта.
Пример вывода: 'name: Ivan position manager'
"""

# пиши свой код здесь
return f"name: {self.name} position: {self.position}"

def __hash__(self):
return id(self)
Expand All @@ -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):
Expand All @@ -97,4 +107,4 @@ def __init__(self, name: str, salary: int):
Задача: реализовать конструктор класса, используя конструктор родителя
"""

# пиши свой код здесь
super().__init__(name, Manager.position, salary)
19 changes: 15 additions & 4 deletions tasks/practice5/team.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
"""
Задача:
Expand All @@ -27,31 +30,39 @@ 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 not isinstance(member, Employee):
raise TypeError
self.__members.add(member)

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]:
"""
Задача: реализовать метод возвращения списка участков команды та,
чтобы из вне нельзя было поменять список участников внутри класса
"""

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

def show(self) -> None:
"""
Expand Down