Skip to content
Draft
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
20 changes: 20 additions & 0 deletions module11/MODULE_11.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# Module 11: Python standard and third-party libraries

## Module Description
This is module 11.


---

# TODO List

- [x] Create a directory for module 11.
- [x] Create pull request from 'module11' branch to 'master' branch
- [x] Add homeworks
- [ ] Create a new branch from 'module11' branch
- [ ] Create a corresponding directory for the homework
- [ ] Add homework files to the directory
- [ ] Create a pull request from 'hw*' branch to 'module11' branch
- [ ] After checkup with instructor merge pull request
- [ ] Add homework descriptions to MODULE_11.md
- [ ] Merge pull request
33 changes: 33 additions & 0 deletions module11/hw1/email.csv
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
Email,Id,First name,Last name
laura@example.com,2070,Laura,Grey
craig@example.com,4081,Craig,Johnson
mary@google.com,9346,Mary,Jenkins
jamie@example.com,5079,Jamie,Smith
laura@example.com,2070,Laura,Grey
craig@example.com,4081,Craig,Johnson
gary@google.com,9123,Gary,Jenkins
jamie@example.com,5079,Jamie,Smith
laura@example.com,2070,Laura,Grey
craig@example.com,4081,Craig,Johnson
max@google.com,4567,Max,Jenkins
jamie@example.com,5079,Jamie,Smith
laura@example.com,2070,Laura,Grey
craig@example.com,4081,Craig,Johnson
lucy@google.com,9678,Lucy,Jenkins
jamie@example.com,5079,Jamie,Smith
laura@example.com,2070,Laura,Grey
craig@example.com,4081,Craig,Johnson
mary@email.ru,9346,Mary,Jenkins
jamie@example.com,5079,Jamie,Smith
laura@example.com,2070,Laura,Grey
craig@example.com,4081,Craig,Johnson
mary@gemail.ru,9346,Mary,Jenkins
jamie@example.com,5079,Jamie,Smith
laura@example.com,2070,Laura,Grey
craig@example.com,4081,Craig,Johnson
mary@email.ru,9346,Mary,Jenkins
jamie@example.com,5079,Jamie,Smith
laura@example.com,2070,Laura,Grey
craig@example.com,4081,Craig,Johnson
mary@email.ru,9346,Mary,Jenkins
jamie@example.com,5079,Jamie,Smith
83 changes: 83 additions & 0 deletions module11/hw1/module_11_1.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
# Домашнее задание по теме "Обзор сторонних библиотек Python"
"""
Задача:
1. Выберите одну или несколько сторонних библиотек Python, например, requests, pandas, numpy, matplotlib, pillow.
2. После выбора библиотек(-и) изучите документацию к ней(ним),
ознакомьтесь с их основными возможностями и функциями.
К каждой библиотеке дана ссылка на документацию ниже.

Если вы выбрали:
1. requests - запросить данные с сайта и вывести их в консоль.
2. pandas - считать данные из файла,
выполнить простой анализ данных (на своё усмотрение) и вывести результаты в консоль.
3. numpy - создать массив чисел, выполнить математические операции с массивом и вывести результаты в консоль.
4. matplotlib - визуализировать данные с помощью библиотеки любым удобным для вас инструментом из библиотеки.
5. pillow - обработать изображение, например, изменить его размер, применить эффекты и сохранить в другой формат.

В приложении к ссылке на GitHub напишите комментарий о возможностях,
которые предоставила вам выбранная библиотека и как вы расширили возможности Python с её помощью.

Примечания:
1. Можете выбрать не более 3-х библиотек для изучения.
2. Желательно продемонстрировать от 3-х функций/классов/методов/операций из каждой выбранной библиотеки.
"""


""" REQUESTS """
import requests

# 1. Отправка GET-запроса на публичное API для получения данных
response = requests.get("https://jsonplaceholder.typicode.com/posts")
print("Статус запроса:", response.status_code)

# 2. Вывод первых нескольких записей из JSON-ответа
data = response.json()
for post in data[:3]: # 3 первых поста
print(f"ID: {post['id']}, Заголовок: {post['title']}")

# 3. Отправка POST-запроса для создания новой записи
new_post = {
"userId": 11,
"title": "Post title",
"body": "Post body"
}
post_response = requests.post("https://jsonplaceholder.typicode.com/posts", json=new_post)
print("Новый пост создан, статус:", post_response.status_code)
print("Ответ сервера:", post_response.json())


""" PANDAS """
import pandas as pd

# 1. Загрузка данных из CSV-файла
df = pd.read_csv("email.csv")
print("Первые строки таблицы:")
print(df.head())

# 2. Основной анализ данных: получение описательной статистики
print("\nСтатистика по данным:")
print(df.describe(include='all'))

# 3. Фильтрация данных: выбор строк по условию
filtered_df = df[df['Email'].str.endswith("@google.com")] # отбор записей, где идентификатор больше 5000
print("\nПользователи с email на google.com:")
print(filtered_df)


""" NUMPY """
import numpy as np

# 1. Создание массива
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])
print("Массив:", arr)

#2. Выполнение математических операций
print("Сумма элементов массива:", np.sum(arr))
print("Среднее значение:", np.mean(arr))
print("Квадратный корень из каждого элемента:", np.sqrt(arr))

# 3. Создание двумерного массива и выполнение операций
matrix = np.array([[1, 2, 3, 4],
[5, 6, 7, 8]])
print("\nМатрица:\n", matrix)
print("Транспортированная матрица:\n", np.transpose(matrix))
Binary file added module11/hw1/numpy.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added module11/hw1/pandas.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added module11/hw1/requests.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added module11/hw3/img.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
67 changes: 67 additions & 0 deletions module11/hw3/module_11_3.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
#
"""
Задание:
Необходимо создать функцию, которая принимает объект (любого типа) в качестве аргумента
и проводит интроспекцию этого объекта, чтобы определить его тип, атрибуты, методы, модуль, и другие свойства.

1. Создайте функцию introspection_info(obj), которая принимает объект obj.
2. Используйте встроенные функции и методы интроспекции Python для получения информации о переданном объекте.
3. Верните словарь или строки с данными об объекте, включающий следующую информацию:
- Тип объекта.
- Атрибуты объекта.
- Методы объекта.
- Модуль, к которому объект принадлежит.
- Другие интересные свойства объекта, учитывая его тип (по желанию).
"""


def introspection_info(obj):
# Получаем тип объекта
obj_type = type(obj).__name__

# Получаем атрибуты объекта (без методов)
attributes = [attr for attr in dir(obj) if not callable(getattr(obj, attr)) and not attr.startswith("__")]

# Получаем методы объекта
methods = [method for method in dir(obj) if callable(getattr(obj, method)) and not method.startswith("__")]

# Получаем модуль, в котором определен объект
obj_module = obj.__class__.__module__

# Дополнительные свойства, если необходимо
extra_properties = {
"is_class": isinstance(obj, type),
"docstring": obj.__doc__,
"repr": repr(obj)
}

# Возвращаем словарь с интроспекцией
return {
'type': obj_type,
'attributes': attributes,
'methods': methods,
'module': obj_module,
'extra_properties': extra_properties
}


# Пример использования
class ExampleClass:
def __init__(self, name, value):
self.name = name
self.value = value


def greet(self):
return f"Hello, {self.name}!"


def say_goodbye(self):
return f"Bye, {self.name}!"


example = ExampleClass("John", 42)

# Интроспекция объекта
info = introspection_info(example)
print(info)