Skip to content

22ПМИ-1 Фролов #141

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 1 commit 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
10 changes: 6 additions & 4 deletions tasks/practice1/practice1.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,26 +2,28 @@ def concatenate_strings(a: str, b: str) -> str:
"""
Функция для сложения двух строк.
Результат сложения запишите в переменную result.

:param a: число
:param b: число
:return: результат сложения
"""

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

return result
result = a + b
return result


def calculate_salary(total_compensation: int) -> float:
"""
Функция расчета зарплаты, которую сотрудник получит после
вычета налогов. Ставка налогообложения равна 13%.

:param total_compensation: сумма зарплаты до вычета налога
:return: сумма заплаты после вычета налога
"""

# пиши свой код здесь
tax_rate = 0.13
tax_amount = total_compensation * tax_rate
result = total_compensation - tax_amount

return result
# pytest tests/test_practice5.py
32 changes: 28 additions & 4 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 @@ -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 = round(random.uniform(100, 1000000), 2)
return amount


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

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


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

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


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

# пиши код здесь
return result
text = text.strip().capitalize()
text = text.replace('"', '').replace("'", "")
for word in uncultured_words:
text = text.replace(word, '#' * len(word))
return text


def create_request_for_loan(user_info: str) -> str:
Expand All @@ -101,4 +116,13 @@ def create_request_for_loan(user_info: str) -> str:
"""

# пиши код здесь
return result
try:
last_name, first_name, middle_name, birth_date, loan_amount = user_info.split(',')
result = (f"Фамилия: {last_name}\n"
f"Имя: {first_name}\n"
f"Отчество: {middle_name}\n"
f"Дата рождения: {birth_date}\n"
f"Запрошенная сумма: {loan_amount}")
return result
except ValueError:
raise ValueError
34 changes: 30 additions & 4 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 csv
import re


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

# пиши свой код здесь
words = re.findall(r'\b[a-zA-Z]{2,}\b', text)
words_count = {}

return {}
for word in words:
word = word.lower()
if not any(char.isdigit() for char in word):
if word in words_count:
words_count[word] += 1
else:
words_count[word] = 1

return words_count


def exp_list(numbers: List[int], exp: int) -> List[int]:
Expand All @@ -42,7 +54,7 @@ def exp_list(numbers: List[int], exp: int) -> List[int]:

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

return []
return [number ** exp for number in numbers]


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

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


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

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

return 0
path_to_file = get_path_to_file()
with path_to_file.open(newline='') as csvfile:
reader = csv.DictReader(csvfile)
unique_elements = set()
for row in reader:
unique_elements.add(row[header])

return len(unique_elements)
13 changes: 13 additions & 0 deletions tasks/practice4/practice4.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,5 +39,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():
result = search_phone(value, name)
if result:
return result

elif isinstance(content, list):
for item in content:
result = search_phone(item, name)
if result:
return result

return None
22 changes: 22 additions & 0 deletions tasks/practice5/employee.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,13 +39,25 @@ def __init__(self, name: str, position: str, salary: int):
"""

# пиши свой код здесь
if not isinstance(salary, int):
raise ValueError("Salary must be an integer")

self.name = name
self.position = position
self._salary = salary

try:
self.position_level = get_position_level(self.position)
except NoSuchPositionError:
self.position_level = -1

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

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

def __eq__(self, other: object) -> bool:
"""
Expand All @@ -56,6 +68,12 @@ def __eq__(self, other: object) -> bool:
"""

# пиши свой код здесь
if not isinstance(other, Employee):
raise TypeError("Comparison only possible between Employee instances")
try:
return get_position_level(self.position) == get_position_level(other.position)
except NoSuchPositionError:
raise ValueError("Invalid position for comparison")

def __str__(self):
"""
Expand All @@ -64,6 +82,7 @@ def __str__(self):
"""

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

def __hash__(self):
return id(self)
Expand All @@ -83,6 +102,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 +119,4 @@ def __init__(self, name: str, salary: int):
"""

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

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

def add_member(self, member: Employee) -> None:
"""
Expand All @@ -36,6 +39,10 @@ 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,6 +51,13 @@ 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]:
"""
Expand All @@ -52,6 +66,16 @@ def get_members(self) -> Set[Employee]:
"""

# пиши свой код здесь
try:
return self.__members.copy()
except Exception as e:
print(f"Error getting members: {e}")

def __str__(self):
"""
Задача: реализовать строковое представление объекта.
"""
return f'team: {self.name} manager: {self.manager.name} number of members: {len(self.__members)}'

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