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 @@ -9,7 +9,7 @@ def concatenate_strings(a: str, b: str) -> str:
"""

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

result = a + b
return result


Expand All @@ -23,5 +23,5 @@ def calculate_salary(total_compensation: int) -> float:
"""

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

result = total_compensation * 0.87
return result
26 changes: 19 additions & 7 deletions tasks/practice2/practice2.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import random
from typing import Iterable

UNCULTURED_WORDS = ('kotleta', 'pirog')
Expand All @@ -13,6 +14,7 @@ def greet_user(name: str) -> str:
"""

# пиши код здесь
greeting = f"Привет, {name}, надеюсь, ты сдал питон!"
return greeting


Expand All @@ -29,6 +31,7 @@ def get_amount() -> float:
"""

# пиши код здесь
amount = random.randint(10000, 100000000) / 100
return amount


Expand All @@ -43,6 +46,10 @@ def is_phone_correct(phone_number: str) -> bool:
"""

# пиши код здесь
if len(phone_number) == 12 and all(i.isdigit() for i in phone_number[2:]) and phone_number[:2] == '+7':
result = True
else:
result = False
return result


Expand All @@ -59,7 +66,7 @@ def is_amount_correct(current_amount: float, transfer_amount: str) -> bool:
"""

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


def moderate_text(text: str, uncultured_words: Iterable[str]) -> str:
Expand All @@ -76,7 +83,10 @@ def moderate_text(text: str, uncultured_words: Iterable[str]) -> str:
:param uncultured_words: список запрещенных слов
:return: текст, соответсвующий правилам
"""

result = text.lower().strip()
result = result.replace('"', '').replace("'", '').replace(uncultured_words[0], '#######').replace(
uncultured_words[1], '#####')
result = result[0].upper() + result[1:]
# пиши код здесь
return result

Expand All @@ -85,20 +95,22 @@ def create_request_for_loan(user_info: str) -> str:
"""
Генерирует заявку на кредит на основе входящей строки.
Формат входящий строки:

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

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

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

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

data = user_info.split(',')
result = 'Фамилия: ' + data[0] + '\nИмя: ' + data[1] + '\nОтчество: ' + data[2] + '\nДата рождения: ' + data[
3] + '\nЗапрошенная сумма: ' + data[4]
# пиши код здесь
return result
29 changes: 23 additions & 6 deletions tasks/practice3/practice3.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
from pathlib import Path
from typing import Dict, Any, List, Optional
import re
import csv


def count_words(text: str) -> Dict[str, int]:
Expand Down Expand Up @@ -27,8 +29,14 @@ def count_words(text: str) -> Dict[str, int]:
"""

# пиши свой код здесь
result = {}

return {}
mask = r'\b[a-z]+\b'
text = text.lower().strip()
word_list = re.findall(mask, text)
for word in word_list:
result[word] = word_list.count(word)
return result


def exp_list(numbers: List[int], exp: int) -> List[int]:
Expand All @@ -41,8 +49,8 @@ def exp_list(numbers: List[int], exp: int) -> List[int]:
"""

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

return []
result = [i**exp for i in numbers]
return result


def get_cashback(operations: List[Dict[str, Any]], special_category: List[str]) -> float:
Expand All @@ -57,7 +65,12 @@ def get_cashback(operations: List[Dict[str, Any]], special_category: List[str])
:param special_category: список категорий повышенного кешбека
:return: размер кешбека
"""

result = 0
for i in operations:
if i['category'] in special_category:
result += i['amount']*0.05
else:
result += i['amount']*0.01
return result


Expand Down Expand Up @@ -100,5 +113,9 @@ def csv_reader(header: str) -> int:
"""

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

return 0
with open(get_path_to_file()) as r_file:
file_reader = csv.DictReader(r_file)
elements = set()
for element in file_reader:
elements.add(element[header])
return len(elements)
14 changes: 12 additions & 2 deletions tasks/practice4/practice4.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 != 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 != None:
return result
24 changes: 21 additions & 3 deletions tasks/practice5/employee.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@

def get_position_level(position_name: str) -> int:
"""
Функция возвращает уровень позиции по ее названию.
Функция возвращает уровень позиции по ее названию.
Если должности нет в базе поднимается исключение `NoSuchPositionError(position_name)`
"""
try:
Expand All @@ -37,7 +37,15 @@ 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:
Expand All @@ -46,7 +54,7 @@ def get_salary(self) -> int:
"""

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

return self._salary
def __eq__(self, other: object) -> bool:
"""
Задача: реализовать метод сравнение двух сотрудников, чтобы все тесты проходили.
Expand All @@ -56,6 +64,12 @@ def __eq__(self, other: object) -> bool:
"""

# пиши свой код здесь
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):
"""
Expand All @@ -64,6 +78,7 @@ def __str__(self):
"""

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

def __hash__(self):
return id(self)
Expand All @@ -83,6 +98,8 @@ def __init__(self, name: str, salary: int, language: str):
"""

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


class Manager(Employee):
Expand All @@ -98,3 +115,4 @@ def __init__(self, name: str, salary: int):
"""

# пиши свой код здесь
super().__init__(name, self.position, salary)
18 changes: 15 additions & 3 deletions tasks/practice5/team.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,14 +28,19 @@ def __init__(self, name: str, manager: Manager):
"""

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

self.name = name
self.manager = manager
self.__members = set()
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:
"""
Expand All @@ -44,15 +49,21 @@ def remove_member(self, member: Employee) -> None:
"""

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

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

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

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:
"""
DO NOT EDIT!
Expand All @@ -65,3 +76,4 @@ def show(self) -> None:
этого метода
"""
print(self)