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

HW13: Andrei Kot #80

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
Empty file added src/CW/__init__.py
Empty file.
28 changes: 28 additions & 0 deletions src/CW/task_13_1.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
"""Создать метод класса get_counter. Создать три объекта класса. Вызвать через класс метод get_counter."""


class Count:
__COUNTER = 0

def __init__(self):
Count.__COUNTER += 1
self.__a = 9

@classmethod
def get_counter(cls):
print(Count.__COUNTER)

@classmethod
def add(cls, x, y):
print(x + y)


# testing
if __name__ == '__main__':
c1 = Count()
c2 = Count()
c3 = Count()
Count.get_counter()
c2.get_counter()
Count.add(2, 3)
c2.add(3, 2)
25 changes: 25 additions & 0 deletions src/CW/task_13_2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
"""Создать статичный метод add_numbers для класса Math. Метод возвращает сумму двух переданных чисел."""


class Math:
__pi = 3.14

def __init__(self):
self.__a = 5

@staticmethod
def add_numbers(x, y):
Math.__pi = 2
return x + y

def a(self):
print(Math.__pi)


# testing
if __name__ == '__main__':
m = Math()
m.a()
print(Math.add_numbers(3, 5))
m.a()
Math.add_numbers(2,3)
35 changes: 35 additions & 0 deletions src/CW/task_13_4.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
"""Создать класс Book. Атрибуты: количество страниц, год издания,
автор, цена. Добавить валидацию в конструкторе на
ввод корректных данных. Создать иерархию ошибок."""


class CountPagesException(Exception):
def __init__(self, page_count, message="Page count must be positive integer value"):
self.__page_count = page_count
self.__message = message
super().__init__(message)

def __str__(self):
return f'{self.__page_count} -> {self.__message}'


class Book:
page_count: int
year: int
author: str
price: int

def __init__(self, page_count, year, author, price):
if page_count > 0 and type(page_count) == int:
self.page_count = page_count
else:
raise CountPagesException(page_count)

self.year = year
self.author = author
self.price = price


# testing
if __name__ == '__main__':
b = Book(0, 1990, 'Somebody', 200)
Empty file added src/CW/test/__init__.py
Empty file.
Empty file.
2 changes: 2 additions & 0 deletions src/CW/test/arithmitic/add.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
def my_add(x, y):
return x + y
2 changes: 2 additions & 0 deletions src/CW/test/arithmitic/sub.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
def sub(x, y):
return x - y
3 changes: 3 additions & 0 deletions src/CW/test/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from src.CW.test.arithmitic import add

print(add.my_add(2, 3))
Empty file added src/HW/__init__.py
Empty file.
26 changes: 26 additions & 0 deletions src/HW/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
"""
1. Создать класс Matrix.
2. Атрибуты - data(содержит саму матрицу - список списков), n, m.
3. Определить конструктор(с параметрами(передача размерности: n, m и диапазона случайных чисел: a, b),
по-умолчанию (матрица 5 на 5 где все элементы равны нулю), копирования) ,
4. Переопределить магический метод str для красивого вывода.
5. Описать функции, которые принимают на вход объект класса Matrix. Функции позволяют искать
максимальный элемент матрицы, минимальный, сумму всех элементов.
6. Создать в файле main.py матрицу. Воспользоваться всеми описанными функциями и методами
"""

from src.HW.matrix_utils import matrix_classes, matrix_funcs

if __name__ == '__main__':
m1 = matrix_classes.Matrix()
print(m1)

m2 = matrix_classes.Matrix(3, 3, [-100, 100])
print(m2)

m3 = matrix_classes.Matrix(m2)
print(m3)

print(matrix_funcs.find_min_matrix_element(m2))
print(matrix_funcs.find_max_matrix_element(m2))
print(matrix_funcs.find_sum_matrix_elements(m2))
Empty file added src/HW/matrix_utils/__init__.py
Empty file.
44 changes: 44 additions & 0 deletions src/HW/matrix_utils/matrix_classes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
from random import randint


class Matrix:

def __init__(self, *args) -> None:
arg_len = len(args)
if arg_len == 0:
self.__n = 5
self.__m = 5
self.__data = []
self.__data = [[0 for i in range(self.__n)] for j in range(self.__m)]
elif arg_len == 3:
self.__n = args[0]
self.__m = args[1]
self.__a = args[2][0]
self.__b = args[2][1]
self.__data = []
self.__fill_random_el()
elif arg_len == 1 and type(args[0]) == Matrix:
self.__n = args[0].__n
self.__m = args[0].__m
self.__data = args[0].__data
else:
raise Exception('Invalid data: incorrect number of parameters')

def __fill_random_el(self):
self.__data = [[randint(self.__a, self.__b) for i in range(self.__n)] for j in range(self.__m)]

def __str__(self):
result = []
for i in self.__data:
result.append(str(i) + '\n')
result = ''.join(result)
return result

@property
def data(self):
return self.__data


if __name__ == '__main__':
m1 = Matrix()
print(str(m1))
21 changes: 21 additions & 0 deletions src/HW/matrix_utils/matrix_funcs.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
from src.HW.matrix_utils.matrix_classes import Matrix


def find_max_matrix_element(matrix: Matrix) -> int or float:
return max([max(i) for i in matrix.data])


def find_min_matrix_element(matrix: Matrix) -> int or float:
return min([min(i) for i in matrix.data])


def find_sum_matrix_elements(matrix: Matrix) -> int or float:
return sum([sum(i) for i in matrix.data])


if __name__ == '__main__':
m1 = Matrix(5, 5, [-10, 10])
print(str(m1))
print(find_max_matrix_element(m1))
print(find_min_matrix_element(m1))
print(find_sum_matrix_elements(m1))