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

Матвеев Данил 13ИП212 #19

Open
wants to merge 2 commits 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
150 changes: 150 additions & 0 deletions Practic/Лекция 2/lec2_13ip212.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
{
"cells": [
{
"cell_type": "markdown",
"id": "c324bbd3",
"metadata": {},
"source": [
"# Решения задач по Python"
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "04b82e13",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Некорректная строка пропущена: # swallow-speeds.txt\n",
"Некорректная строка пропущена: # Airspeed velocities of unladen African swallow (m.s-1)\n",
"Некорректная строка пропущена: # Invalid data is indicated by #\n",
"Некорректная строка пропущена: \n",
"Некорректная строка пропущена: 99.9 #\n",
"Некорректная строка пропущена: 0.0 #\n",
"Средняя скорость: 10.31 м/с\n"
]
}
],
"source": [
"\n",
"# Задача 1: Средняя скорость африканской ласточки с обработкой исключений\n",
"\n",
"def calculate_average_speed(filename):\n",
" try:\n",
" with open(filename, 'r') as file:\n",
" speeds = []\n",
" for line in file:\n",
" try:\n",
" speed = float(line.strip())\n",
" speeds.append(speed)\n",
" except ValueError:\n",
" print(f\"Некорректная строка пропущена: {line.strip()}\")\n",
" if speeds:\n",
" return sum(speeds) / len(speeds)\n",
" else:\n",
" raise ValueError(\"Файл не содержит корректных данных.\")\n",
" except FileNotFoundError:\n",
" print(f\"Файл {filename} не найден.\")\n",
" except Exception as e:\n",
" print(f\"Произошла ошибка: {e}\")\n",
"\n",
"# Пример вызова функции\n",
"filename = 'swallow-speeds.txt' # Убедитесь, что файл находится в текущей директории\n",
"average_speed = calculate_average_speed(filename)\n",
"if average_speed is not None:\n",
" print(f\"Средняя скорость: {average_speed:.2f} м/с\")\n"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "a6b52039",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"(-2 3.5)\n",
"(4 0.5 -2)\n",
"Ошибка: Вектор содержит недопустимые элементы.\n",
"None\n"
]
}
],
"source": [
"\n",
"# Задача 2: Проверка на действительные числа в векторе\n",
"\n",
"def str_vector(vector):\n",
" try:\n",
" if not all(isinstance(x, (int, float)) for x in vector):\n",
" raise TypeError(\"Вектор содержит недопустимые элементы.\")\n",
" return f\"({' '.join(map(str, vector))})\"\n",
" except TypeError as e:\n",
" print(f\"Ошибка: {e}\")\n",
"\n",
"# Пример вызова функции\n",
"print(str_vector([-2, 3.5])) # Допустимый вектор\n",
"print(str_vector((4, 0.5, -2))) # Допустимый вектор\n",
"print(str_vector([1, 'a', 3])) # Недопустимый вектор\n"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "9fed66f2",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"8\n",
"Ошибка: Определение 0^0 не существует.\n"
]
}
],
"source": [
"\n",
"# Задача 3: Поведение 0^0 с генерацией исключения\n",
"\n",
"def powr(a, b):\n",
" if a == 0 and b == 0:\n",
" raise ValueError(\"Определение 0^0 не существует.\")\n",
" return a ** b\n",
"\n",
"# Пример вызова функции\n",
"try:\n",
" print(powr(2, 3)) # 8\n",
" print(powr(0, 0)) # Должно вызвать исключение\n",
"except ValueError as e:\n",
" print(f\"Ошибка: {e}\")\n"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.10.0"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
1 change: 1 addition & 0 deletions Practic/Лекция 2/sonnet18.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
ыаыавфыыфвф
24 changes: 24 additions & 0 deletions Practic/Лекция 2/swallow-speeds.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# swallow-speeds.txt
# Airspeed velocities of unladen African swallow (m.s-1)
# Invalid data is indicated by #

10.1
12.1
9.8
8.9
10.3
9.2
9.6
9.2
10.1
11.7
12.0
10.0
99.9 #
8.8
11.9
12.0
0.0 #
9.9
9.8
10.2
121 changes: 121 additions & 0 deletions Practic/Практическая_04/PR4_13ip212.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
{
"cells": [
{
"cell_type": "markdown",
"id": "438b5252",
"metadata": {},
"source": [
"\n",
"# Решение задач\n",
"\n",
"## Задание 1\n",
"\n",
"1. Изменить базовый класс `BankAccount` для проверки номера счета на соответствие алгоритму Луна.\n",
"2. Изменить класс `CurrentAccount` для реализации свободного овердрафта с установкой лимита.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "01b1e16d",
"metadata": {},
"outputs": [],
"source": [
"\n",
"def luhn_check(account_number):\n",
" \"\"\"Проверка номера счета по алгоритму Луна.\"\"\"\n",
" digits = [int(d) for d in str(account_number)][::-1]\n",
" for i in range(len(digits)):\n",
" if i % 2 == 1:\n",
" digits[i] *= 2\n",
" if digits[i] > 9:\n",
" digits[i] -= 9\n",
" return sum(digits) % 10 == 0\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "f0056c4e",
"metadata": {},
"outputs": [],
"source": [
"\n",
"class BankAccount:\n",
" def __init__(self, account_number, balance=0):\n",
" if not luhn_check(account_number):\n",
" raise ValueError(\"Некорректный номер счета!\")\n",
" self.account_number = account_number\n",
" self.balance = balance\n",
"\n",
" def deposit(self, amount):\n",
" if amount <= 0:\n",
" raise ValueError(\"Сумма депозита должна быть положительной.\")\n",
" self.balance += amount\n",
"\n",
" def withdraw(self, amount):\n",
" if amount > self.balance:\n",
" raise ValueError(\"Недостаточно средств на счете.\")\n",
" self.balance -= amount\n",
"\n",
" def __str__(self):\n",
" return f\"Счет №{self.account_number}, Баланс: {self.balance}\"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "c304b632",
"metadata": {},
"outputs": [],
"source": [
"\n",
"class CurrentAccount(BankAccount):\n",
" def __init__(self, account_number, balance=0, overdraft_limit=0):\n",
" super().__init__(account_number, balance)\n",
" self.overdraft_limit = overdraft_limit\n",
"\n",
" def withdraw(self, amount):\n",
" if amount > self.balance + self.overdraft_limit:\n",
" raise ValueError(\"Превышен лимит овердрафта.\")\n",
" self.balance -= amount\n",
"\n",
" def __str__(self):\n",
" return f\"Счет №{self.account_number}, Баланс: {self.balance}, Лимит овердрафта: {self.overdraft_limit}\"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "ba1e59dc",
"metadata": {},
"outputs": [],
"source": [
"\n",
"# Пример использования\n",
"\n",
"try:\n",
" acc = BankAccount(\"79927398713\", 1000) # Корректный номер счета\n",
" print(acc)\n",
" acc.deposit(500)\n",
" print(acc)\n",
" acc.withdraw(200)\n",
" print(acc)\n",
"except ValueError as e:\n",
" print(e)\n",
"\n",
"try:\n",
" current_acc = CurrentAccount(\"79927398713\", 500, 300) # Корректный номер счета\n",
" print(current_acc)\n",
" current_acc.withdraw(700) # В пределах лимита\n",
" print(current_acc)\n",
" current_acc.withdraw(200) # Превышение лимита\n",
"except ValueError as e:\n",
" print(e)\n"
]
}
],
"metadata": {},
"nbformat": 4,
"nbformat_minor": 5
}
80 changes: 80 additions & 0 deletions Practic/Практическая_08/PR8_13ip212.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
{
"cells": [
{
"cell_type": "markdown",
"id": "9d9856f9",
"metadata": {},
"source": [
"\n",
"# Практическая работа: Дискретные преобразования Фурье\n",
"\n",
"## Задание\n",
"Сравнить скорость выполнения алгоритма `np.fft.fft` из библиотеки NumPy и непосредственной (собственной) реализации формулы.\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "4c4f797c",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Сравнение скорости выполнения:\n"
]
}
],
"source": [
"\n",
"import numpy as np\n",
"\n",
"# Размер данных\n",
"n = 1024\n",
"\n",
"# Случайные значения функции\n",
"data = np.random.random(n)\n",
"\n",
"# Собственная реализация дискретного преобразования Фурье\n",
"def dft_manual(x):\n",
" n = len(x)\n",
" m = np.arange(n)\n",
" k = m.reshape((n, 1))\n",
" w = np.exp(-2j * np.pi * k * m / n)\n",
" return np.dot(w, x)\n",
"\n",
"# Сравнение скорости выполнения\n",
"print(\"Сравнение скорости выполнения:\")\n",
"\n",
"# Собственная реализация\n",
"%timeit dft_manual(data)\n",
"\n",
"# NumPy FFT\n",
"%timeit np.fft.fft(data)\n"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.10.0"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
Loading