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
28 changes: 20 additions & 8 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 @@ -12,7 +13,7 @@ def greet_user(name: str) -> str:
:return: приветствие
"""

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


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

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


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

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


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

# пиши код здесь
text=text.strip()
for n in text:
if (n=='/'or n=="'" or n=='"'):
text=text.replace(n,'')
result=text[:1].upper()+text[1:].lower()
for nword in uncultured_words:
result=result.replace(nword,'#'*len(nword))
return result


Expand All @@ -99,6 +111,6 @@ def create_request_for_loan(user_info: str) -> str:
: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
37 changes: 26 additions & 11 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 @@ -26,9 +27,17 @@ def count_words(text: str) -> Dict[str, int]:
значение - количество вхождений слов в текст
"""

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

return {}
Dict={}
punctuation_marks=['!','"',"'",',','-','.',':',';','?','_','`']
for mark in punctuation_marks:
text=text.replace(mark,' ')
data=text.lower().split()
for word in data:
if word.isalpha() and len(word)>1:
Dict[word.lower()]=data.count(word)
elif (word[:-1].isalpha() and ( word[-1] == ',' or word[-1] == '?' or word[-1] == '!' or word[-1] == '.' and len(word) > 1)):
Dict[word[:-1].lower()] = data.count(word[:-1])
return Dict


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

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

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


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 range(len(operations)):
if len(special_category)>0 and operations[i]['category']==special_category[0]:
result+=operations[i]['amount']*0.05
else:
result+= operations[i]['amount'] * 0.01
return result


Expand Down Expand Up @@ -98,7 +111,9 @@ def csv_reader(header: str) -> int:
:param header: название заголовка
:return: количество уникальных элементов в столбце
"""

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

return 0
column=[]
with open(get_path_to_file()) as csvfile:
read = csv.DictReader(csvfile)
for r in read:
column.append(r[header])
return len(set(column))
11 changes: 9 additions & 2 deletions tasks/practice4/practice4.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,13 @@ def search_phone(content: Any, name: str) -> Optional[str]:
:return: номер телефона пользователя или None
"""

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

stack=[content]
while stack:
now=stack.pop()
if(isinstance(now,list)):
stack.extend(now)
elif(isinstance(now,dict)):
if now.get('name')==name:
return now.get('phone')
stack.extend(now.values())
return None
24 changes: 17 additions & 7 deletions tasks/practice5/employee.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,15 +37,20 @@ def __init__(self, name: str, position: str, salary: int):
"""
Задача: реализовать конструктор класса, чтобы все тесты проходили
"""
if(isinstance(name,str) and isinstance(position,str) and 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,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:
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 @@ -81,8 +91,8 @@ def __init__(self, name: str, salary: int, language: str):
"""
Задача: реализовать конструктор класса, используя конструктор родителя
"""

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


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

# пиши свой код здесь
super().__init__(name, Manager.position, salary)
23 changes: 19 additions & 4 deletions tasks/practice5/team.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,31 +27,43 @@ 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 TypeError

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

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



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

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

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

def __str__(self):
return f"team: {self.name} manager: {self.manager.name} number of members: {len(self.__members)}"