Skip to content
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

Урок_8 #1810

Open
wants to merge 1 commit into
base: master
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
29 changes: 29 additions & 0 deletions Урок 8. Практическое задание/task_1.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,32 @@
Второй, с декоратором @staticmethod, должен проводить валидацию числа, месяца
и года (например, месяц — от 1 до 12). Проверить работу полученной структуры на реальных данных.
"""

class Data:

def __init__(self, date):
self.day_month_year = date

@classmethod
def make_attributes(cls, date):
temp_list = date.split('-')
Data.day = int(temp_list[0])
Data.month = int(temp_list[1])
Data.year = int(temp_list[2])

@staticmethod
def validate():
if Data.day not in range(1, 31):
return "imposible day num"
if Data.month not in range(1, 12):
return "imposible day month"
if Data.year <= 0:
return "imposible day year"
return f"current date is: {Data.day}/{Data.month}/{Data.year}"

# def __str__(self):
# print(f"Date is {Data.make_attributes}")


Data.make_attributes("10-04-2023")
print(Data.validate())
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

выполнено

17 changes: 17 additions & 0 deletions Урок 8. Практическое задание/task_2.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,20 @@
Проверьте его работу на данных, вводимых пользователем. При вводе пользователем нуля
в качестве делителя программа должна корректно обработать эту ситуацию и не завершиться с ошибкой.
"""

class MyException(Exception):
txt = "IMPOSIBLE!!!!"

def __str__(self):
return self.txt

number = int(input('Please enter number '))
devider = int(input('Please enter devider '))

try:
if devider == 0:
raise MyException
except MyException as err:
print(err)
else:
print(f'result of devision is {number/devider:.2f}')
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

выполнено

23 changes: 23 additions & 0 deletions Урок 8. Практическое задание/task_3.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,26 @@

Класс-исключение должен контролировать типы данных элементов списка.
"""

class MyException(Exception):
txt = "PROBLEM!!!! Value can't be converted to int"

def __str__(self):
return self.txt


final_list = []
while True:
val = input("Please enter number or 'stop' for finish ")
if val == 'stop':
break
else:
try:
if val.isnumeric():
final_list.append(int(val))
else:
raise MyException
except MyException as err:
print(err)

print(final_list)
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

выполнено

133 changes: 133 additions & 0 deletions Урок 8. Практическое задание/task_4_5_6.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,3 +19,136 @@
Подсказка: постарайтесь по возможности реализовать в проекте
«Склад оргтехники» максимум возможностей, изученных на уроках по ООП.
"""

class NoSpace(Exception):
txt = "There is no free space in this stock"

def __str__(self):
return self.txt


class UnknownItem(Exception):
txt = "I don't know this item"

def __str__(self):
return self.txt


class NotInt(Exception):
txt = "PROBLEM!!!! Value can't be converted to int"

def __str__(self):
return self.txt

class Stock:
list_of_equipment = {
'Printer': [],
'Scaner': [],
'Copier': []
}

def __init__(self, size):
self.size = size

def add_to_stock(self, item):
if self.size > 0:
if item.class_name() == 'Printer':
self.list_of_equipment['Printer'].append(item)
self.size -= 1
elif item.class_name() == 'Scaner':
self.list_of_equipment['Scaner'].append(item)
self.size -= 1
elif item.class_name() == 'Copier':
self.list_of_equipment['Scaner'].append(item)
self.size -= 1
else:
raise UnknownItem
else:
raise NoSpace
return "item was successfully added"

def take_of_item(self, item):
if item.class_name() == 'Printer':
self.list_of_equipment['Printer'].remove(item)
self.size += 1
elif item.class_name() == 'Scaner':
self.list_of_equipment['Scaner'].remove(item)
self.size += 1
elif item.class_name() == 'Copier':
self.list_of_equipment['Scaner'].remove(item)
self.size += 1
else:
raise UnknownItem

def show_equipment(self):
res = "There are in stock: \n"
for key in self.list_of_equipment:
if len(self.list_of_equipment[key]) > 0:
res += f"{key}s = {len(self.list_of_equipment[key])} \n"
res += "models are: \n"
for el in self.list_of_equipment[key]:
res += f"{el.firm_name} model {el.model} \n"
else:
res += f"{key} no in stock\n"
return res


class Equipment:
voltage = 220

def __init__(self, name, model):
self.firm_name = name
self.model = model

def class_name(self):
return self.__class__.__name__

def __str__(self):
return self.firm_name


class Printer(Equipment):
paper_size = 'A3'
pass


class Copier(Equipment):
color = False
pass


class Scaner(Equipment):
scan_speed_list_per_minute = 10
pass

go_on = True
stock_capisity = input("Please enter stock capasity, or enter 'cancel'")
while go_on:
try:
if stock_capisity == 'cancel':
break
else:
if stock_capisity.isnumeric():
stock = Stock(int(stock_capisity))
go_on = False
else:
raise NotInt
except NotInt as e:
print(e)

try:
pr1 = Printer("HP", 'ls-1010')
stock.add_to_stock(pr1)
print(stock.show_equipment())
pr2 = Printer("Keosera", '2323')
stock.add_to_stock(pr2)
print(stock.show_equipment())
scaners = [['lenovo', '2324'], ['LG', '234-5'], ['Samsung', 'sg-123']]
for el in scaners:
stock.add_to_stock(Scaner(el[0],el[1]))
print(stock.show_equipment())
print("_____________")
stock.take_of_item(pr2)
print(stock.show_equipment())
except (NoSpace, UnknownItem) as e:
print(e)
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

выполнено

40 changes: 40 additions & 0 deletions Урок 8. Практическое задание/task_7.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,43 @@
создав экземпляры класса (комплексные числа) и выполнив сложение и умножение созданных экземпляров.
Проверьте корректность полученного результата.
"""

import re


class Complexus:

def __init__(self, comlex_number):
if comlex_number[0] == '-':
comlex_number = comlex_number[1:-1]
if comlex_number.find('-') != -1:
self.first = int("-" + re.split('[- ]', comlex_number)[0])
self.second = int('-' + re.split('[- ]', comlex_number)[1].replace('i', ''))
else:
self.first = int("-" + re.split('[+ ]', comlex_number)[0])
self.second = int('-' + re.split('[+ ]', comlex_number)[1].replace('i', ''))
else:
if comlex_number.find('-') != -1:
self.first = int(re.split('[- ]', comlex_number)[0])
self.second = int('-' + re.split('[- ]', comlex_number)[1].replace('i', ''))
else:
self.first = int(re.split('[+ ]', comlex_number)[0])
self.second = int('-' + re.split('[+ ]', comlex_number)[1].replace('i', ''))

def __str__(self):
return f"{self.first}{self.second}i"

def __add__(self, other):
a = self.first + other.first
b = self.second + other.second
return Complexus(f"{a}{b}i")

def __mul__(self, other):
a = (self.first * other.first) - (self.second * other.second)
b = (self.first * other.second) + (self.second * other.first)
return Complexus(f"{a}{b}i")

c1 = Complexus('5-7i')
c2 = Complexus('4-5i')
print(f"sum of c1 and c2 will be {c1 + c2}")
print(f"multiplication of c1 and c2 will be {c1 * c2}")
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

выполнено