Initial commit

parents
# Лабораторные работы по дисциплине программирование на Python третьего семестра.
## Отчёты
[ЛР1](./lab1/README.md)
[ЛР2](./lab2/README.md)
[ЛР3](./lab3/README.md)
[ЛР4](./lab4/README.md)
[ЛР5](./lab5/README.md)
[ЛР6](./lab6/README.md)
[ЛР7](./lab7/README.md)
"""
Простой калькулятор, позволяет ввести 2 числа и операцию и вычисляет результат.
"""
def calculate(x, y, op):
"""
Считает x op y, где x и y - числа любого типа, а op - строка
"""
if (op == "+"):
return x + y
elif (op == "-"):
return x - y
elif (op == "*"):
return x * y
elif (op == "/"):
return x / y
else:
return None
def test_substraction():
"""
Тест, приверяет вычитание
"""
assert calculate("10", "5", "-") == 5
def test_multiplication():
"""
Тест, приверяет умножение
"""
assert calculate(10, "5", "*") == 50
def test_addition():
"""
Тест, приверяет сложение
"""
assert calculate("10", 5.0, "+") == 15
def test_division():
"""
Тест, приверяет деление
"""
assert calculate("10", "5", "/") == 2
test_substraction()
test_multiplication()
test_addition()
test_division()
input1 = input("Enter first number: ")
input2 = input("Enter second number: ")
inputOp = input("Enter the operation: ")
print(calculate(input1, input2, inputOp))
"""
Игра угадай число. Программа угадывает число на заданном диапазоне бинарным поиском
"""
def guess_number(start, end):
numbers = [i for i in range(start, end+1)]
while True:
guess = numbers[len(numbers)//2 - 1]
guess_count = 0
print(f"{guess} больше(>), меньше(<) или и есть число(=)?")
verdict = input()
guess_count += 1
if (verdict == ">"):
numbers = numbers[len(numbers)//2:]
elif (verdict == "<"):
numbers = numbers[:len(numbers)//2]
elif (verdict == "="):
return {"Number" : numbers[len(numbers)//2 - 1], "Guesses:" : guess_count}
return None
print(guess_number(1, 10))
# Программирование Python лабораторная работа 1
def outer_function(a, b):
print("Внешняя функция вызвана с аргументами:", a, b)
def inner_closure(c, d):
print("Аргументы внешней функции:", a, b)
print("Аргументы внутренней функции:", c, d)
result = a + b + c + d
return result
return inner_closure
closure = outer_function(1, 2)
result = closure(3, 4)
print("Результат:", result)
"""
Простой калькулятор, позволяет ввести 2 числа и операцию и вычисляет результат.
"""
import logging as log
log.basicConfig(level=log.INFO)
def log_wrapper(func):
def wrapper(*args, **kwargs):
log.info(f"Called {func.__name__} with args {args} and kwargs {kwargs}")
result = func(*args, **kwargs)
log.info(f"{func.__name__} returned {result}")
return result
return wrapper
@log_wrapper
def calculate(x, op, y):
"""
Считает x op y, где x и y - числа любого типа, а op - строка
"""
return eval(f"{x} {op} {y}")
print(calculate("9", "+", "10"))
from functools import partial
def calc_decay(n0, t, t_half):
return n0 * 2 ** (t/t_half)
# период полураспада в годах
isotopes_half_lifes = {
"C": 5730,
"Cd": 9*10**15,
"H": 12.3,
"Np": 2.1 * 10**6
}
isotopes_decay_fucns = dict()
for isotope in isotopes_half_lifes.keys():
isotopes_half_life = isotopes_half_lifes[isotope]
decay_func = partial(calc_decay, t_half=isotopes_half_life)
isotopes_decay_fucns[isotope] = decay_func
t = 100
n0 = 1e10
for isotope in isotopes_decay_fucns.keys():
print(f"Через {t} лет останется {isotopes_decay_fucns[isotope](n0=n0, t=t)} ядер {isotope}")
def calculate(x, y, op):
"""
Считает x op y, где x и y - числа любого типа, а op - строка
"""
if (op == "+"):
return x + y
elif (op == "-"):
return x - y
elif (op == "*"):
return x * y
elif (op == "/"):
return x / y
else:
return None
"""
import unittest
# tests using unittest
class TestStringMethods(unittest.TestCase):
def test_sum(self):
self.assertEqual(calculate("5", "+", "3"), 8)
def test_division(self):
self.assertEqual(calculate("15", "/", "3"), 5)
def test_substitution(self):
self.assertEqual(calculate("15", "-", "5"), 10)
def test_multiplication(self):
self.assertEqual(calculate("5", "*", "3"), 15)
if __name__ == '__main__':
unittest.main()
"""
#tests for pytest
def test_sum():
assert calculate("5", "+", "3") == 8
def test_division():
assert calculate("15", "/", "3") == 5
def test_substitution():
assert calculate("5", "-", "3") == 2
def test_multiplication():
assert calculate("5", "*", "3") == 15
# Программирование Python лабораторная работа 2
В задании 1.4 pytest не может импортировать файл 1.4.py, поэтому main.py - ссылка на 1.4.py
1.4.py
\ No newline at end of file
import math
import unittest
def convert_precision(tolerance):
"""
Конвертирует tolerance в порядок точности.
Args:
tolerance (float): Значение tolerance.
Returns:
int: Порядок точности.
Raises:
ValueError: При невозможности определить порядок точности.
"""
if tolerance == 0:
return 0
return abs(math.floor(math.log10(abs(tolerance))))
def calculate(x, op, y, tolerance=1e-6):
"""
Считает x op y, где x и y - числа любого типа, а op - строка операции.
Args:
x (float): Первое число.
op (str): Операция (+, -, *, /).
y (float): Второе число.
tolerance (float): Точность вычислений (по умолчанию 1e-6).
Returns:
float: Результат вычисления с округлением до указанной точности.
Raises:
ValueError: При неверном значении операции.
"""
if op not in ['+', '-', '*', '/']:
raise ValueError("Неверная операция")
if (op == "+"):
result = x + y
elif (op == "-"):
result = x - y
elif (op == "*"):
result = x * y
elif (op == "/"):
result = x / y
# Округление результата до нужной точности
precision = convert_precision(tolerance)
rounded_result = round(result, precision)
return rounded_result
class TestCalculator(unittest.TestCase):
def test_convert_precision(self):
self.assertEqual(convert_precision(0), 0)
self.assertEqual(convert_precision(1e-9), 9)
self.assertEqual(convert_precision(1e-5), 5)
def test_calculate_addition(self):
self.assertAlmostEqual(calculate(1, '+', 2), 3, places=8)
def test_calculate_subtraction(self):
self.assertAlmostEqual(calculate(5, '-', 3), 2, places=8)
def test_calculate_multiplication(self):
self.assertAlmostEqual(calculate(4, '*', 5), 20, places=8)
def test_calculate_division(self):
self.assertAlmostEqual(calculate(10, '/', 2), 5, places=8)
def test_calculate_with_custom_tolerance(self):
self.assertAlmostEqual(calculate(0.1, '+', 0.2), 0.3, places=8)
if __name__ == '__main__':
unittest.main()
import math
import unittest
import numpy
def convert_precision(tolerance):
"""
Конвертирует tolerance в порядок точности.
Args:
tolerance (float): Значение tolerance.
Returns:
int: Порядок точности.
Raises:
ValueError: При невозможности определить порядок точности.
"""
if tolerance == 0:
return 0
return abs(math.floor(math.log10(abs(tolerance))))
def calculate(action, *args, tolerance=1e-6):
"""
Производит действие action над аргументами *args.
Args:
action (string): Дейсвие, может быть одним из
+, -, *, /, medium, variance, std_deviation, median, q2, q3
*args (float): Числа над которыми будет произведено действие actoin
tolerance (float): Точность вычислений (по умолчанию 1e-6).
Returns:
float: Результат вычисления с округлением до указанной точности.
Raises:
ValueError: При неверном значении операции.
"""
if action not in ['+', '-', '*', '/', 'medium', \
'variance', 'std_deviation', 'median', 'q2', 'q3']:
raise ValueError("Неверная операция")
if (action == '+'):
result = sum(args)
elif (action == '-'):
result = args[0]
for i in range(1, len(args)):
result -= args[i]
elif (action == '*'):
result = 1
for i in range(len(args)):
result *= args[i]
elif (action == '/'):
result = args[0]
for i in range(1, len(args)):
result /= args[i]
elif (action == 'medium'):
return numpy.mean(args)
elif (action == 'variance'):
return numpy.var(args)
elif (action == 'std_deviation'):
return numpy.std(args)
elif (action == 'median'):
return numpy.median(args)
elif (action == 'q2'):
return numpy.median(args)
elif (action == 'q3'):
return numpy.percentile(args, 75)
else:
raise ValueError("Неверная операция")
# Округление результата до нужной точности
precision = convert_precision(tolerance)
rounded_result = round(result, precision)
return rounded_result
class TestCalculator(unittest.TestCase):
def test_convert_precision(self):
self.assertEqual(convert_precision(0), 0)
self.assertEqual(convert_precision(1e-9), 9)
self.assertEqual(convert_precision(1e-5), 5)
def test_calculate_addition(self):
self.assertAlmostEqual(calculate('+', 1, 2), 3, places=8)
def test_calculate_subtraction(self):
self.assertAlmostEqual(calculate('-', 5, 3), 2, places=8)
def test_calculate_multiplication(self):
self.assertAlmostEqual(calculate('*', 4, 5), 20, places=8)
def test_calculate_division(self):
self.assertAlmostEqual(calculate('/', 10, 2), 5, places=8)
def test_calculate_with_custom_tolerance(self):
self.assertAlmostEqual(calculate('+', 0.1, 0.2), 0.3, places=8)
def test_stat_operations(self):
self.assertAlmostEqual(calculate('medium', 1, 2, 3, 4), 2.5, places=8)
self.assertAlmostEqual(calculate('variance', 1, 2, 3, 4), 1.25, places=8)
self.assertAlmostEqual(calculate('std_deviation', 1, 2, 3, 4), 0.7071067811865476, places=8)
self.assertAlmostEqual(calculate('median', 1, 2, 3, 4), 2, places=8)
self.assertAlmostEqual(calculate('q2', 1, 2, 3, 4), 2, places=8)
self.assertAlmostEqual(calculate('q3', 1, 2, 3, 4), 3, places=8)
if __name__ == '__main__':
unittest.main()
# Программирование Python лабораторная работа 3
login
password
def two_sum(lst, target):
pairs = (len(lst), len(lst))
for i in range(len(lst)):
for j in range(len(lst)):
if (lst[i] + lst[j] == target and (i, j) < pairs):
pairs = (i, j)
return pairs
lst = list(range(1,10))
target = 8
result = two_sum(lst, target)
print(result)
def two_sum(lst, target):
pairs = (len(lst), len(lst))
for i in range(len(lst)):
if ((target - lst[i]) in lst and (i, lst.index(target - lst[i])) < pairs):
pairs = (i, lst.index(target - lst[i]))
return pairs
lst = list(range(1,10))
target = 8
result = two_sum(lst, target)
print(result)
from random import shuffle
def two_sum(lst, target):
pairs = (len(lst), len(lst))
for i in range(len(lst)):
if ((target - lst[i]) in lst and (i, lst.index(target - lst[i])) < pairs):
pairs = (i, lst.index(target - lst[i]))
return pairs
def two_sum_hashed_all(lst, target):
pairs = []
for i in range(int(len(lst)/2)):
if ((target - lst[i]) in lst and i != lst.index(target - lst[i]) and (lst.index(target - lst[i]), i) not in pairs):
pairs.append((i, lst.index(target - lst[i])))
return pairs
lst = list(range(1,100))
target = 8
result = two_sum_hashed_all(lst, target)
print(result)
from functools import cache
import time
@cache
def fibonacci_cache(n):
if n <= 1:
return n
return fibonacci_cache(n-1) + fibonacci_cache(n-2)
my_dict = {0: 0, 1: 1}
def fibonacci_dict(n):
if n not in my_dict:
my_dict[n] = fibonacci_dict(n-1) + fibonacci_dict(n-2)
return my_dict[n]
start = time.time()
result = fibonacci_dict(30)
time_taken_dict = time.time() - start
print(f"dict result:{result}, time {time_taken_dict:.6f}")
start = time.time()
result = fibonacci_cache(30)
time_taken_cache = time.time() - start
print(f"cache result:{result}, time {time_taken_cache:.6f}")
import smtplib
from email.message import EmailMessage
textfile = "mes.txt"
loginfile = "login"
passwdfile = "password"
with open(textfile) as fp:
msg = EmailMessage()
msg.set_content(fp.read())
with open(loginfile) as fp:
login = fp.read()
with open(passwdfile) as fp:
password = fp.read()
sender = login
reciever = login
msg['Subject'] = f'The contence of {textfile}'
msg['From'] = sender
msg['To'] = reciever
server = smtplib.SMTP('smtp.gmail.com:587')
server.ehlo()
server.starttls()
server.login(login,password)
server.send_message(msg)
server.quit()
import requests
from bs4 import BeautifulSoup
url = "https://yandex.com.am/weather"
response = requests.get(url)
bs = BeautifulSoup(response.text,"lxml")
temp = bs.find('span', 'temp__value temp__value_with-unit')
summary = bs.find('div', 'title-icon__text');
print(f"Температура: {temp.text}")
print(f"{summary.text}")
import matplotlib.pyplot as plt
import numpy as np
import requests
def f1(x):
return x**2
def f2(x):
return np.sin(x)
def get_weather_data(format):
url = f"https://wttr.in/?format={format}"
try:
response = requests.get(url)
response.raise_for_status()
return response.json()
except requests.RequestException as e:
print(f"Ошибка при запросе к серверу: {e}")
return None
fig1, ax1 = plt.subplots(figsize=(10, 6))
x = np.linspace(-np.pi, np.pi, 400)
ax1.plot(x, f1(x), label='y = x^2')
ax1.plot(x, f2(x), label='y = sin(x)')
ax1.set_title('Графики двух функций')
ax1.legend()
weather_data= get_weather_data("j2")
dates = list()
temps = list()
for weather_info in weather_data['weather']:
dates.append(weather_info['date'])
temps.append(int(weather_info['avgtempC']))
fig2, ax2 = plt.subplots(figsize=(10, 6))
ax2.plot(dates, temps)
ax2.set_title('График средней температуры на 3 дня')
ax2.set_xlabel('Дата')
ax2.set_ylabel('Средняя температура (°C)')
ax2.grid(True)
plt.show()
# Программирование Python лабораторная работа 4
## Комплект 1
Задачи не потребовали изучения чего-либо нового или каких либо уникальных решений.
## Комплект 2
### 2.1 Отправка почты через smtplib
Самым интересным было применение файла .gitignore для хранения логина и пароля от ящика, в остальном, это на 80% пример использования библиотеки.
![Полученное письмо](/2.1 mail.png "Полученное письмо")
### 2.2 Парсинг погоды
Решил парсить с яндекс погоды (тк wttr.in упал), выводится тепература в данный момент и скорость ветра.
### 2.3 Графики с matplotlib
Применил передачу форматов wttr.in. Получение данных в json, парсинг были тривиальными, как и вывод полученных данных на график.
from random import randint
class RandomNumberIterator:
def __init__(self, amount, start, end):
self.range_start = start
self.range_end = end
self.amount = amount
self.current = -1
self.rand_list = list(randint(self.range_start, self.range_end) for i in range(self.amount))
def __iter__(self):
return self
def __next__(self):
if (self.current < self.amount - 1):
self.current += 1
return self.rand_list[self.current]
raise StopIteration
for i in RandomNumberIterator(10, 1, 10):
print(i)
from random import randint
def RandomNumberGenerator(start, end, amount):
for _ in range(amount):
yield randint(start, end)
for i in RandomNumberGenerator(0, 10, 10):
print(i)
def fib_gen(num):
count, a, b = 0, 0, 1
while (count < num):
yield a
a, b, count = b, a + b, count + 1
def plus_10_gen(seq):
for i in seq:
yield i + 10
for i in plus_10_gen(fib_gen(10)):
print(i)
import csv
countries = {}
with open('world-cities.csv') as f:
reader = csv.DictReader(f)
for i in reader:
if i["country"] not in countries.keys():
countries[i["country"]] = [i["name"]]
else:
countries[i["country"]].append(i["name"])
while True:
cities_to_find= input("Введите города для поиска (через пробел): ").split()
for city_to_find in cities_to_find:
for country, cities in countries.items():
if (city_to_find.lower() in [city.lower() for city in cities]):
print(f"{city_to_find} находится в {country}")
import time
class Timer:
def __init__(self):
self.start_time = 0
self.end_time = 0
self.elapsed_time = 0
def __enter__(self):
self.start_time = time.perf_counter()
return self
def __exit__(self, exc_type, exc_value, exc_traceback):
self.end_time = time.perf_counter()
self.elapsed_time = self.end_time - self.start_time
def fib_gen(num):
count, a, b = 0, 0, 1
while (count < num):
yield a
a, b, count = b, a + b, count + 1
fib_list = list()
with Timer() as timer1:
#fib_list = list(fib_gen(1_000_000))
print(fib_gen(1_000_000))
#print(fib_list)
print(timer1.elapsed_time)
import math
import unittest
import numpy
def convert_precision(tolerance):
if tolerance == 0:
return 0
return abs(math.floor(math.log10(abs(tolerance))))
def calculate(action, *args, tolerance=1e-6):
if action not in ['+', '-', '*', '/', 'medium', \
'variance', 'std_deviation', 'median', 'q2', 'q3']:
raise ValueError("Неверная операция")
if (action == '+'):
result = sum(args)
elif (action == '-'):
result = args[0]
for i in range(1, len(args)):
result -= args[i]
elif (action == '*'):
result = 1
for i in range(len(args)):
result *= args[i]
elif (action == '/'):
result = args[0]
for i in range(1, len(args)):
result /= args[i]
elif (action == 'medium'):
return numpy.mean(args)
elif (action == 'variance'):
return numpy.var(args)
elif (action == 'std_deviation'):
return numpy.std(args)
elif (action == 'median'):
return numpy.median(args)
elif (action == 'q2'):
return numpy.median(args)
elif (action == 'q3'):
return numpy.percentile(args, 75)
else:
raise ValueError("Неверная операция")
# Округление результата до нужной точности
precision = convert_precision(tolerance)
rounded_result = round(result, precision)
return rounded_result
class BatchCalculatorContextManager:
def __init__(self, file):
self.filename = file
self.file = None
self.lines = None
self.line_count = None
def __enter__(self):
self.file = open(self.filename, "r")
self.lines = self.file.readlines()
self.line_count = len(self.lines)
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.file.close()
if exc_val:
raise
def perform_calculation(self):
for line in self.lines:
a, op, b = line.split()
yield calculate(op, float(a), float(b))
with BatchCalculatorContextManager('file.txt') as calc:
for i in calc.perform_calculation():
print(f"{i}")
from pymongo import MongoClient
class MongoDBConnectionContextManager(object):
def __init__(self, host='localhost', port=27017, username='admin', password='admin'):
self.host = host
self.port = port
self.username = username
self.passwd = password
self.connection = None
def __enter__(self):
self.connection = MongoClient(
self.host,
self.port,
username = self.username,
password = self.passwd,
authMechanism="SCRAM-SHA-1")
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.connection.close()
with MongoDBConnectionContextManager(host='localhost', port=27017, username='myUserAdmin', password='abc123') as mcm:
lst = mcm.connection['myshinynewdb']['user']
user = lst.find({'age': 205})
print(next(user))
# Программирование Python лабораторная работа 4
## Комплект 1
Почти все решения задач комплекта 1 были тривиальными изменениями примеров из документации Python.
### 1.4
Для разнообразия решил взять список всех городов, чтобы прасить города и страны от туда, на удивление работает оно достаточно быстро.
Города взяты (отсюда)[https://github.com/datasets/world-cities].
## Комплект 2
### 2.1
Задача сводится к поиску разницы между временем в момент вызова enter и exit.
1_000_000 чисел фибоначи найти не получилось, остановился на 100_000 (за 0.3855c)
### 2.2
По умолчанию подсчет ведется из file.txt, функция подсчета реализована как итератор.
### 2.3
Было много проблем с docker, в конце концов установил mongodb локально и это сработало.
![Получение записи из mongodb](/2.3.png "Получение записи из mongodb]")
1 + 2
2 - 3
4 * 4
4 / 16
This source diff could not be displayed because it is too large. You can view the blob instead.
import pytest
from calc import calculate, convert_precision
def test_convert_precision():
assert convert_precision(0) == 0
assert convert_precision(1) == 0
assert convert_precision(0.1) == 1
assert convert_precision(0.01) == 2
assert convert_precision(0.000001) == 6
def test_addition():
assert calculate('+', 1, 2) == 3
assert calculate('+', 10, 20) == 30
assert calculate('+', -1, 1) == 0
def test_subtraction():
assert calculate('-', 5, 3) == 2
assert calculate('-', 10, 20) == -10
assert calculate('-', -1, 1) == -2
def test_multiplication():
assert calculate('*', 2, 3) == 6
assert calculate('*', 0, 5) == 0
assert calculate('*', -2, 3) == -6
def test_division():
assert calculate('/', 15, 3) == 5
assert calculate('/', 6, 3) == 2
assert calculate('/', 10, 2) == 5
@pytest.mark.parametrize("values, expected", [
([1, 2, 3, 4, 5], 3),
([-1, 0, 1], 0),
])
def test_medium(values, expected):
assert calculate('medium', *values) == pytest.approx(expected)
@pytest.mark.parametrize("values, expected", [
([1, 2, 3, 4, 5], 2.0),
([10, 11, 3, 4, 5], 10.64),
])
def test_variance(values, expected):
assert calculate('variance', *values) == pytest.approx(expected)
@pytest.mark.parametrize("values, expected", [
([1, 2, 3, 4, 5], 1.414214),
([-1, 0, 1], 0.816497),
])
def test_std_deviation(values, expected):
assert calculate('std_deviation', *values) == pytest.approx(expected)
def test_median():
assert calculate('median', [1, 3, 5]) == 3
assert calculate('median', [-1, 0, 1]) == 0
def test_q2():
assert calculate('q2', [1, 3, 5]) == 3
assert calculate('q2', [-1, 0, 1]) == 0
def test_q3():
assert calculate('q3', [1, 3, 5]) == pytest.approx(4.0)
assert calculate('q3', [-1, 0, 1]) == pytest.approx(0.5)
# Запуск тестов
if __name__ == '__main__':
pytest.main([__file__, "-v"])
import pytest
from calc import calculate, convert_precision
@pytest.mark.parametrize("input_value, expected_output", [
(0, 0),
(1, 0),
(0.1, 1),
(0.01, 2),
(0.000001, 6),
])
def test_convert_precision(input_value, expected_output):
assert convert_precision(input_value) == expected_output
def test_addition():
assert calculate('+', 1, 2) == 3
assert calculate('+', 10, 20) == 30
assert calculate('+', -1, 1) == 0
def test_subtraction():
assert calculate('-', 5, 3) == 2
assert calculate('-', 10, 20) == -10
assert calculate('-', -1, 1) == -2
def test_multiplication():
assert calculate('*', 2, 3) == 6
assert calculate('*', 0, 5) == 0
assert calculate('*', -2, 3) == -6
def test_division():
assert calculate('/', 6, 3) == 2
assert calculate('/', 10, 2) == 5
assert calculate('/', 0, 5) == 0
@pytest.mark.parametrize("values, expected", [
([1, 2, 3, 4, 5], 3),
([-1, 0, 1], 0),
])
def test_medium(values, expected):
assert calculate('medium', *values) == expected
@pytest.mark.parametrize("values, expected", [
([1, 2, 3, 4, 5], 2),
([-1, 0, 1], 0.6666666666666666),
])
def test_variance(values, expected):
assert calculate('variance', *values) == pytest.approx(expected)
@pytest.mark.parametrize("values, expected", [
([1, 2, 3, 4, 5], 1.414214),
([-1, 0, 1], 0.816497),
])
def test_std_deviation(values, expected):
assert calculate('std_deviation', *values) == pytest.approx(expected)
@pytest.mark.parametrize("values, expected", [
([1, 3, 5], 3),
([-1, 0, 1], 0),
])
def test_median(values, expected):
assert calculate('median', *values) == expected
@pytest.mark.parametrize("values, expected", [
([1, 3, 5], 3),
([-1, 0, 1], 0),
])
def test_q2(values, expected):
assert calculate('q2', *values) == expected
@pytest.mark.parametrize("values, expected", [
([1, 3, 5], 4),
([-1, 0, 1], 0.5),
])
def test_q3(values, expected):
assert calculate('q3', *values) == expected
import math
import unittest
import numpy as np
def convert_precision(tolerance):
if tolerance == 0:
return 0
try:
return abs(math.floor(math.log10(abs(tolerance))))
except Exception as e:
print(f"Ошибка при конверсии точности: {e}")
return 0
def calculate(action, *args, tolerance=1e-6):
if action not in ['+', '-', '*', '/', 'medium', \
'variance', 'std_deviation', 'median', 'q2', 'q3']:
raise ValueError("Неверная операция")
try:
if (action == '+'):
result = sum(args)
elif (action == '-'):
result = args[0]
for i in range(1, len(args)):
result -= args[i]
elif (action == '*'):
result = 1
for i in range(len(args)):
result *= args[i]
elif (action == '/'):
result = args[0]
for i in range(1, len(args)):
result /= args[i]
elif (action == 'medium'):
result = np.mean(args)
elif (action == 'variance'):
result = np.var(args)
elif (action == 'std_deviation'):
result = np.std(args)
elif (action == 'median'):
result = np.median(args)
elif (action == 'q2'):
result = np.median(args)
elif (action == 'q3'):
result = np.percentile(args, 75)
else:
raise ValueError("Неверная операция")
precision = convert_precision(tolerance)
rounded_result = round(result, precision)
return rounded_result
except Exception as e:
print(f"Ошибка при вычислении: {e}")
raise
class BatchCalculatorContextManager:
def __init__(self, file):
self.filename = file
self.file = None
self.lines = None
self.line_count = None
def __enter__(self):
try:
self.file = open(self.filename, "r")
if not self.file:
raise IOError("Не удалось открыть файл")
self.lines = self.file.readlines()
self.line_count = len(self.lines)
return self
except Exception as e:
print(f"Ошибка при открытии файла или чтении строк: {e}")
raise
def __exit__(self, exc_type, exc_val, exc_tb):
try:
if self.file:
self.file.close()
except Exception as e:
print(f"Ошибка при закрытии файла: {e}")
def perform_calculation(self):
for line in self.lines:
try:
a, op, b = line.split()
yield calculate(op, float(a), float(b))
except ValueError as ve:
print(f"Неверное выражение в строке: {ve}")
except Exception as e:
print(f"Ошибка при обработке строки: {e}")
try:
with BatchCalculatorContextManager('file.txt') as calc:
for i in calc.perform_calculation():
print(i)
except IOError as io_error:
print(f"Ошибка при работе с файлом: {io_error}")
except Exception as general_exception:
print(f"Неожиданная ошибка: {general_exception}")
1 + 2
2 - 3
4 * 4
4 / 16
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment