Skip to content

22ПИ-3 Савельев #135

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
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
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -129,3 +129,5 @@ dmypy.json

# Pyre type checker
.pyre/

*.DS_Store
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
36 changes: 32 additions & 4 deletions tasks/practice2/practice2.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import random

from typing import Iterable

UNCULTURED_WORDS = ('kotleta', 'pirog')
Expand All @@ -11,7 +13,7 @@ def greet_user(name: str) -> str:
:param name: имя пользователя
:return: приветствие
"""

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

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

# пиши код здесь
amount = round(random.randint(10000, 1000000) * random.random(), 2)
return amount


Expand All @@ -41,8 +44,20 @@ def is_phone_correct(phone_number: str) -> bool:
:return: буленовское значение - bool: True - если номер корректны,
False - если номер некорректный
"""


# пиши код здесь
result = True

if len(phone_number) != 12:
result = False

if phone_number[:2] != "+7":
result = False

if not phone_number[2:].isdigit():
result = False

return result


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

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


Expand All @@ -78,7 +94,15 @@ def moderate_text(text: str, uncultured_words: Iterable[str]) -> str:
"""

# пиши код здесь
return result
text = " ".join(text.split())
text = text.capitalize()
text = text.replace('"', '').replace("'", '')

for w in uncultured_words:
w_length = len(w)
text = text.replace(w, '#' * w_length)

return text


def create_request_for_loan(user_info: str) -> str:
Expand All @@ -99,6 +123,10 @@ def create_request_for_loan(user_info: str) -> str:
:param user_info: строка с информацией о клиенте
:return: текст кредитной заявки
"""

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

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

# пиши свой код здесь
result = {}
words = text.split()

return {}
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]:
Expand All @@ -41,8 +53,11 @@ def exp_list(numbers: List[int], exp: int) -> List[int]:
"""

# пиши свой код здесь
result = []

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

return result


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


result = 0.0

for operation in operations:
if operation['category'] not in special_category:
result += operation['amount'] * 0.01
else:
result += operation['amount'] * 0.05

return result


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

# пиши свой код здесь
file_path = get_path_to_file()
result = set()

with open(file_path, 'r') as file:
reader = csv.DictReader(file)
for row in reader:
result.add(row[header])

return 0
return len(result)
14 changes: 14 additions & 0 deletions tasks/practice4/practice4.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,4 +40,18 @@ def search_phone(content: Any, name: str) -> Optional[str]:

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

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: 20 additions & 2 deletions tasks/practice5/employee.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,13 +37,19 @@ def __init__(self, name: str, position: str, salary: int):
"""
Задача: реализовать конструктор класса, чтобы все тесты проходили
"""
if not (isinstance(name, str) and isinstance(position, str) and isinstance(salary, int)):
raise ValueError
self.name = name
self.position = position
self._salary = salary

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

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

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

Expand All @@ -54,6 +60,16 @@ def __eq__(self, other: object) -> bool:
Сравнение происходит по уровню позиции см. `get_position_level`.
Если что-то идет не так - бросаются исключения. Смотрим что происходит в тестах.
"""
if isinstance(other, Employee):
try:
first_position = get_position_level(self.position)
second_position = get_position_level(other.position)
if first_position == second_position:
return True
return False
except NoSuchPositionError:
raise ValueError
raise TypeError

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

Expand All @@ -62,6 +78,7 @@ def __str__(self):
Задача: реализовать строковое представление объекта.
Пример вывода: 'name: Ivan position manager'
"""
return f'name: {self.name} position: {self.position}'

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

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

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


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

super().__init__(name, self.position, salary)
# пиши свой код здесь
17 changes: 17 additions & 0 deletions tasks/practice5/team.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,9 @@ def __init__(self, name: str, manager: Manager):
Конструктор должен присвоить значения публичным атрибутам
и инициализировать контейнер `__members`
"""
self.name = name
self.manager = manager
self.__members = set()

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

Expand All @@ -34,6 +37,10 @@ def add_member(self, member: Employee) -> None:
Задача: реализовать метод добавления участника в команду.
Добавить можно только работника.
"""
if isinstance(member, Employee):
self.__members.add(member)
else:
raise TypeError

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

Expand All @@ -42,6 +49,12 @@ def remove_member(self, member: Employee) -> None:
Задача: реализовать метод удаления участника из команды.
Если в команде нет такого участника поднимается исключение `NoSuchMemberError`
"""
if not isinstance(member, Employee):
raise TypeError
if member in self.__members:
self.__members.remove(member)
else:
raise NoSuchMemberError(self.name, member)

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

Expand All @@ -50,9 +63,13 @@ def get_members(self) -> Set[Employee]:
Задача: реализовать метод возвращения списка участков команды та,
чтобы из вне нельзя было поменять список участников внутри класса
"""
return self.__members.copy()

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

def __str__(self) -> str:
return f'team: {self.name} manager: {self.manager.name} number of members: {len(self.__members)}'

def show(self) -> None:
"""
DO NOT EDIT!
Expand Down
Loading