-
Notifications
You must be signed in to change notification settings - Fork 0
Д.з. по модулю 9 "Работа с объектами Python" #175
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
nsa3108
wants to merge
10
commits into
main
Choose a base branch
from
nskorokhodova_first_branch
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
b30e5fc
Д.з. по модулю 9 "Работа с объектами Python"
nsa3108 c928558
Д.з. по модулю 9 "Работа с объектами Python"
nsa3108 eb37aa0
Д.з. по модулю 10 "Библиотеки"
nsa3108 30c0773
Д.з. по модулю 12 задача1
nsa3108 ea386fa
Д.з. по модулю 12 задача1
nsa3108 21dc8c9
исправления по задаче1 лекции 9
nsa3108 b00a5b8
ДЗ модуль 13, задача 1
nsa3108 0502f82
ДЗ модуль 15 задача теоритическая
nsa3108 19feb18
исправления по 12 модулю
nsa3108 6ce9e95
исправления по 15 модулю
nsa3108 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,12 @@ | ||
| #Используя модуль re, найти все команды Git с аргументами в файле Practice/README.md | ||
| import re | ||
|
|
||
|
|
||
| lst = [] | ||
| with open(r"C:\Users\..\Practice\README.md", "r", encoding="utf-8'") as f: | ||
| reg = re.compile(r"git\s\w*") | ||
| for line in f: | ||
| line = line.rstrip('\n') | ||
| lst += re.findall(reg, line) | ||
| for i in lst: | ||
| print(i) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,32 @@ | ||
| from datetime import datetime, timedelta | ||
|
|
||
|
|
||
| def count_working_days(start_date, end_date): | ||
| start_date = datetime.strptime(start_date, "%Y-%m-%d") | ||
| end_date = datetime.strptime(end_date, "%Y-%m-%d") | ||
|
|
||
| holidays = [ | ||
| datetime(2023, 1, 1), | ||
| datetime(2023, 3, 8), | ||
| datetime(2023, 5, 1), | ||
| datetime(2023, 5, 9), | ||
| datetime(2023, 6, 12), | ||
| datetime(2023, 11, 4), | ||
| ] | ||
|
|
||
| working_days = 0 | ||
|
|
||
| current_date = start_date | ||
| while current_date <= end_date: | ||
| if current_date.weekday() < 5 and current_date not in holidays: | ||
| working_days += 1 | ||
|
|
||
| current_date += timedelta(days=1) | ||
| return working_days | ||
|
|
||
|
|
||
| start_date = "2023-01-01" | ||
| end_date = "2023-01-31" | ||
|
|
||
| result = count_working_days(start_date, end_date) | ||
| print("Количество рабочих дней:", result) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,30 @@ | ||
| import os | ||
| import time | ||
| import shutil | ||
|
|
||
|
|
||
| def delete_files_and_folders(path, expiration_time): | ||
| current_time = time.time() | ||
|
|
||
| try: | ||
| for root, dirs, files in os.walk(path): | ||
| for file_name in files: | ||
| file_path = os.path.join(root, file_name) | ||
|
|
||
| creation_time = os.path.getctime(file_path) | ||
|
|
||
| if (current_time - creation_time) > expiration_time: | ||
| os.remove(file_path) | ||
|
|
||
| for dir_name in dirs: | ||
| dir_path = os.path.join(root, dir_name) | ||
|
|
||
| creation_time = os.path.getctime(dir_path) | ||
|
|
||
| if (current_time - creation_time) > expiration_time: | ||
| shutil.rmtree(dir_path) | ||
|
|
||
| print("Файлы и папки, у которых истек срок:", path) | ||
|
|
||
| except Exception as e: | ||
| print("Ошибка при удалении файлов и папок:", str(e)) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,40 @@ | ||
| import pickle | ||
| import random | ||
|
|
||
|
|
||
| class Human: | ||
| def __init__(self, name, surname, age, address): | ||
| self.name = name | ||
| self.surname = surname | ||
| self.age = age | ||
| self.address = address | ||
|
|
||
|
|
||
| def create_humans(num_humans): | ||
| humans = [] | ||
| for _ in range(num_humans): | ||
| name = random.choice(["Иван", "Мария", "Михаил", "Александр", "Алла"]) | ||
| surname = random.choice(["Иванов", "Олешко", "Смирнов", "Моисеев", "Копытова"]) | ||
| age = random.randint(18, 65) | ||
| address = random.choice(["Москва", "Лондон", "Нижний Новгород", "Пермь", "Омск"]) | ||
| human = Human(name, surname, age, address) | ||
| humans.append(human) | ||
| return humans | ||
|
|
||
|
|
||
| def serialize(humans): | ||
| with open("human.data", "wb") as file: | ||
| pickle.dump(humans, file) | ||
|
|
||
|
|
||
| def deserialize(): | ||
| with open("human.data", "rb") as file: | ||
| humans = pickle.load(file) | ||
| for human in humans: | ||
| print(human.name, human.surname, human.age, human.address) | ||
|
|
||
|
|
||
| x = int(input("Введите число ")) | ||
| p = create_humans(x) | ||
| serialize(p) | ||
| deserialize() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,30 @@ | ||
| class ParagraphIterator: | ||
| def __init__(self, text, paragraph_separator): | ||
| self.text = text | ||
| self.paragraph_separator = paragraph_separator | ||
| self.paragraphs = self.text.split(self.paragraph_separator) | ||
| self.index = 0 | ||
|
|
||
| def __iter__(self): | ||
| return self | ||
|
|
||
| def __next__(self): | ||
| if self.index >= len(self.paragraphs): | ||
| raise StopIteration | ||
| else: | ||
| paragraph = self.paragraphs[self.index] | ||
| self.index += 1 | ||
| return paragraph | ||
|
|
||
|
|
||
| text = """ | ||
| В лесу родилась елочка. В лесу она росла. | ||
| Зимой и летом стройная. | ||
| Зеленая была. | ||
| """ | ||
|
|
||
| paragraph_separator = '.' | ||
| paragraphs = ParagraphIterator(text, paragraph_separator) | ||
|
|
||
| for paragraph in paragraphs: | ||
| print(paragraph) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,8 @@ | ||
| def read_file(file_path): | ||
| with open(file_path, 'r') as file: | ||
| for line in file: | ||
| yield line.rstrip('\n') | ||
|
|
||
| file_path = 'C:\Python\python.exe\..\Files\info.txt' | ||
| for line in read_file(file_path): | ||
| print(line) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,14 @@ | ||
| import time | ||
|
|
||
|
|
||
| class MyTime: | ||
| def __enter__(self): | ||
| self._start_time = time.time() | ||
| print("Начало исполнения кода") | ||
|
|
||
| def __exit__(self, exc_type, exc_val, exc_tb): | ||
| print(f"Время исполнения {time.time() - self._start_time}") | ||
|
|
||
|
|
||
| with MyTime(): | ||
| time.sleep(1) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,24 @@ | ||
| import itertools | ||
|
|
||
|
|
||
| def my_iter_merge(arr1, arr2, arr3): | ||
| return list(itertools.chain(arr1 + arr2 + arr3)) | ||
|
|
||
|
|
||
| def my_iter_len(arr): | ||
| return list(filter(lambda x: len(x) >= 5, arr)) | ||
|
|
||
|
|
||
| def my_iter_comb(my_pass): | ||
| for i in itertools.combinations(my_pass, 4): | ||
| print(i) | ||
|
|
||
|
|
||
| first_task = ([1, 2, 3], [4, 5], [6, 7]) | ||
| print(my_iter_merge(*first_task)) | ||
|
|
||
| second_task = (["hello", "i", "write", "cool", "code"]) | ||
| print(my_iter_len(second_task)) | ||
|
|
||
| third_task = "password" | ||
| my_iter_comb(third_task) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,24 @@ | ||
| import socket | ||
| import pickle | ||
|
|
||
| def send_data(data): | ||
| host = 'mynet' | ||
| port = 13579 | ||
|
|
||
| with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: | ||
| s.connect((host, port)) | ||
|
|
||
| send_data = pickle.dumps(data) | ||
| s.sendall(send_data) | ||
|
|
||
| recv_data = s.recv(1024) | ||
|
|
||
| decoded_data = pickle.loads(recv_data) | ||
|
|
||
| return decoded_data | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| encrypted_words = ['par**', 'is***bul', 'Li**on', 'lon**n'] | ||
| decrypted_words = send_data(encrypted_words) | ||
| print(decrypted_words) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,52 @@ | ||
| import socket | ||
| import pickle | ||
|
|
||
| def decrypt_words(encrypted_words): | ||
| dictionary = { | ||
| 'par**': 'Paris', | ||
| 'is***bul': 'Istanbul', | ||
| 'Li**on': 'Lisbon', | ||
| 'lon**n': 'London' | ||
| } | ||
| decrypted_words = [] | ||
|
|
||
| for word in encrypted_words: | ||
| decrypted_word = dictionary.get(word) | ||
| decrypted_words.append(decrypted_word) | ||
|
|
||
| return decrypted_words | ||
|
|
||
|
|
||
| def handle_client(conn): | ||
| recv_data = conn.recv(1024) | ||
|
|
||
| encrypted_words = pickle.loads(recv_data) | ||
|
|
||
| decrypted_words = decrypt_words(encrypted_words) | ||
|
|
||
| send_data = pickle.dumps(decrypted_words) | ||
|
|
||
| conn.sendall(send_data) | ||
|
|
||
| conn.close() | ||
|
|
||
|
|
||
| def start_server(): | ||
| host = 'mynet' | ||
| port = 13579 | ||
|
|
||
| with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: | ||
| s.bind((host, port)) | ||
| s.listen() | ||
|
|
||
| print("Server started.") | ||
|
|
||
| while True: | ||
| conn, addr = s.accept() | ||
| print(f"Client connected: {addr}") | ||
|
|
||
| handle_client(conn) | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| start_server() | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,65 @@ | ||
| import math | ||
| import time | ||
| import threading | ||
| import multiprocessing | ||
|
|
||
|
|
||
| def is_prime(num): | ||
| if num < 2: | ||
| return False | ||
| for i in range(2, int(math.sqrt(num)) + 1): | ||
| if num % i == 0: | ||
| return False | ||
| return True | ||
|
|
||
|
|
||
| def find_primes(end, start=3): | ||
| primes = [] | ||
| for num in range(start, end + 1): | ||
| if is_prime(num): | ||
| primes.append(num) | ||
| return primes | ||
|
|
||
|
|
||
| if __name__ == '__main__': | ||
| t1 = threading.Thread(target=find_primes, args=(10000,)) | ||
| t2 = threading.Thread(target=find_primes, args=(20000, 10001,)) | ||
| t3 = threading.Thread(target=find_primes, args=(30000, 20001,)) | ||
|
|
||
| start_time = time.time() | ||
| t1.start() | ||
| t2.start() | ||
| t3.start() | ||
| print("Потоки запущены") | ||
|
|
||
|
IlyaOrlov marked this conversation as resolved.
|
||
| start = time.perf_counter() | ||
| threads = [] | ||
| for args in ((10000, 3), (20000, 10001), (30000, 20001)): | ||
| thr = threading.Thread(target=find_primes, args=args) | ||
| thr.start() | ||
| threads.append(thr) | ||
| for j in threads: | ||
| j.join() | ||
|
|
||
| print(f'Общее время вычислений потоков в секундах: {time.perf_counter() - start}\n') | ||
|
|
||
| p1 = multiprocessing.Process(target=find_primes, args=(10000,)) | ||
| p2 = multiprocessing.Process(target=find_primes, args=(20000, 10001,)) | ||
| p3 = multiprocessing.Process(target=find_primes, args=(30000, 20001,)) | ||
|
|
||
| start_time = time.time() | ||
| p1.start() | ||
| p2.start() | ||
| p3.start() | ||
| print("Процессы запущены") | ||
|
|
||
| start = time.perf_counter() | ||
| proc = [] | ||
| for args_proc in ((10000, 3), (20000, 10001), (30000, 20001)): | ||
| p = multiprocessing.Process(target=find_primes, args=args_proc) | ||
| p.start() | ||
| proc.append(p) | ||
| for pr in proc: | ||
| pr.join() | ||
|
|
||
| print(f'Общее время вычислений процессов в секундах: {time.perf_counter() - start}\n') | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,50 @@ | ||
| Привести два примера предметной области, для представления которых лучше использовать NoSQL-подход. | ||
| Аргументировать ответ, используя критерии выбора между SQL и NoSQL. | ||
|
|
||
|
|
||
| ______________________________________________________________________________________________________________ | ||
| База данных SQL – это реляционная база данных который организует данные в таблицы со строками и столбцами. SQL означает язык структурированных запросов, который является стандартным языком, используемым для запроса и управления данными в реляционной базе данных. | ||
|
|
||
| Некоторые ключевые характеристики базы данных SQL включают в себя: | ||
|
|
||
| Данные хранятся в таблицах, содержащих строки и столбцы. Каждая строка представляет запись, а каждый столбец представляет атрибут этой записи. | ||
| Между таблицами существуют связи, которые обеспечиваются с помощью внешних ключей. Это обеспечивает целостность данных и уменьшает избыточность. | ||
| Язык SQL используется для запроса данных и управления ими. SQL предоставляет такие команды, как SELECT, INSERT, UPDATE и DELETE, для взаимодействия с базой данных. | ||
| Свойства ACID (атомарность, согласованность, изоляция, долговечность) применяются для обеспечения надежности и целостности данных. Транзакции либо завершаются полностью, либо не завершаются вообще. | ||
|
|
||
| База данных NoSQL — это нереляционная база данных который хранит данные в формате, отличном от строк и столбцов. Базы данных NoSQL бывают разных типов в зависимости от модели данных. Основные типы: | ||
|
|
||
| Хранилища «ключ-значение». Данные хранятся в неструктурированном формате с уникальным ключом для извлечения значений. (Redis). | ||
| Базы данных документов: данные хранятся в формате документа, например JSON. (MongoDB). | ||
| Базы данных графов. Данные хранятся в узлах и ребрах, оптимизированных для взаимоотношений между данными.(Neo4j и JanusGraph). | ||
| Столбчатые базы данных: данные хранятся в столбцах, а не в строках.(Cassandra). | ||
|
|
||
|
|
||
| ________________________________________________________________________________________________________________________- | ||
|
|
||
| 1. Социальные сети. | ||
|
IlyaOrlov marked this conversation as resolved.
|
||
| Социальные сети характеризуются большим объемом данных, высокой скоростью их прихода и изменения, | ||
| а также необходимостью горизонтального масштабирования. | ||
| В такой предметной области лучше использовать NoSQL-подход, так как он позволяет эффективно | ||
| обрабатывать и хранить большие объемы данных с использованием горизонтального масштабирования. | ||
| NoSQL базы данных обеспечивают отказоустойчивость и высокую производительность, | ||
| что очень важно для социальных сетей с миллионами пользователей. | ||
| Реляционность данных - это количество взаимосвязей между данными.Если предметную область можно представить в виде нескольких отдельных словарей - то реляционность слабая. В случае социальных сетей основная информация - это пользователь и его данные. Т.е. у нас получается, один большой список пользователей, и у каждого пользователя - набор атрибутов (имя, аватар, статус и т.д.). | ||
| Пользовательские запросы, в основном, будут такие: найти пользователя по id (это когда мы страничку пользователя открываем), искать пользователей по каким-то другим критериям. Аналогично - для списка музыки, списка видео и т.д. | ||
| Важный момент: сами медиа-файлы обычно хранятся отдельно на диске (как обычные файлы, либо в спец. хранилище, типа Amazon S3); в базу данных (что SQL, что NoSQL) их тащить не надо; в базе данных хранятся только пути к этим файлам в виде обычных строк. | ||
| Поэтому критерии реляционности и пользовательских запросов также говорят в пользу NoSQL: данные нереляционные, пользовательские запросы простые. | ||
|
|
||
|
|
||
| 2. Маркетплэйс ( типа Ozon, Wildberries и т.д.) | ||
| Здесь требуется высокая скорость, т.к. может поступать много запросов, нужно | ||
| делать много изменений ( добавлять/удалять поставщиков, товары и т.д.), | ||
| поэтому лучше использовать NoSQL. | ||
| Но в то же время много различных взаимосвязей товары - цены, покупатели - заказы, | ||
| покупатели - статус заказа и т.д. и большое количество потенциальных запросов | ||
| ( поиск товаров, поиск продавца и т.д.) - решает более эффективно SQL. | ||
| SQL-базы данных обычно используют реляционную модель, где данные хранятся в таблицах, связанных с друг другом. Данные в таблицах структурированы по строгим правилам и могут быть связаны с помощью внешних ключей. Эта структура данных делает SQL-базы данных хорошо подходящими для хранения и обработки структурированных данных. Однако эта модель не подходит для хранения неструктурированных данных, таких как изображения, звуковые файлы, видеоматериалы и т. д. | ||
| Медиа-файлы обычно хранятся отдельно на диске, в базе данных они представлены обычными строками, в которых хранятся пути к этим файлам. | ||
| В случае маркетплейсов данные вроде бы имеют множество взаимосвязей: товары с продавцами, товары с категориями и т.д. Но пользовательские запросы к маркетплейсу, на самом деле, весьма однообразны: нужен список товаров, отфильтрованных по какому-либо признаку. Получается, что нам для хранения данных достаточно большой коллекции документов (товаров), где у каждого документа будет ряд атрибутов (например, категория, цвет, размер, продавец и т.д.). Выносить по правилам реляционных СУБД связи, например, товара и продавца необязательно (тем более конкретный товар всегда жестко привязан к конкретному продавцу). А значит, и объединения таблиц (да и сами таблицы) не требуются. На самом деле, вид, в котором товары отображаются в поисковике маркетплейса, почти повторяет тот вид, в котором они хранятся в его БД. | ||
| Анализ по критериям реляционности и потенциальных запросов обычно выполняется совместно и зачастую сводится к ответу на вопрос: можно ли представить сущности этой предметной области в виде нескольких отдельных словарей. | ||
| Исходя из этого я сделала вывод, что в случае с маркетплэйсами все таки лучше использовать NoSQL. | ||
|
|
||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Ресурс лучше освобождать там же, где он занимался. Т.е. в start_server()
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
хорошо