last lab
This commit is contained in:
14
labPython/lab15/data.txt
Normal file
14
labPython/lab15/data.txt
Normal file
@@ -0,0 +1,14 @@
|
||||
1
|
||||
11
|
||||
10
|
||||
16 11 2002 3
|
||||
14 11 2003 4
|
||||
14 11 2000 5
|
||||
18 11 2000 3
|
||||
14 11 2003 8
|
||||
14 11 2000 7
|
||||
19 11 2005 4
|
||||
14 11 2003 5
|
||||
12 11 2002 5
|
||||
13 11 2000 5
|
||||
2
|
||||
BIN
labPython/lab15/students.bin
Normal file
BIN
labPython/lab15/students.bin
Normal file
Binary file not shown.
79
labPython/lab15/task_1.py
Normal file
79
labPython/lab15/task_1.py
Normal file
@@ -0,0 +1,79 @@
|
||||
class FitnessRecord:
|
||||
def __init__(self, month, year, client_code, duration):
|
||||
self.month = int(month)
|
||||
self.year = int(year)
|
||||
self.client_code = int(client_code)
|
||||
self.duration = int(duration)
|
||||
|
||||
|
||||
def run_task_c4():
|
||||
while True:
|
||||
print("1. Ввести данные и найти результат")
|
||||
print("0. Выход")
|
||||
|
||||
choice = input("Выберите действие: ")
|
||||
|
||||
if choice == "0":
|
||||
break
|
||||
elif choice == "1":
|
||||
try:
|
||||
n_input = input("Введите количество записей N: ")
|
||||
if not n_input.isdigit():
|
||||
raise ValueError("N должно быть целым числом.")
|
||||
n = int(n_input)
|
||||
|
||||
records = []
|
||||
for i in range(n):
|
||||
while True:
|
||||
try:
|
||||
line = input(
|
||||
f"Запись {i + 1} (<Месяц> <Год> <Код> <Часы>): "
|
||||
).split()
|
||||
if len(line) != 4:
|
||||
raise ValueError("Нужно ввести 4 числа через пробел.")
|
||||
|
||||
m, y, c, d = map(int, line)
|
||||
|
||||
if not (1 <= m <= 12):
|
||||
raise ValueError("Месяц: 1-12")
|
||||
if not (2000 <= y <= 2010):
|
||||
raise ValueError("Год: 2000-2010")
|
||||
if not (10 <= c <= 99):
|
||||
raise ValueError("Код: 10-99")
|
||||
if not (1 <= d <= 30):
|
||||
raise ValueError("Часы: 1-30")
|
||||
|
||||
records.append(FitnessRecord(m, y, c, d))
|
||||
break
|
||||
except ValueError as e:
|
||||
print(f"Ошибка ввода: {e}. Попробуйте еще раз.")
|
||||
|
||||
if not records:
|
||||
print("Список пуст.")
|
||||
continue
|
||||
|
||||
best_rec = records[0]
|
||||
for i in range(1, len(records)):
|
||||
current = records[i]
|
||||
if current.duration > best_rec.duration:
|
||||
best_rec = current
|
||||
elif current.duration == best_rec.duration:
|
||||
if (current.year > best_rec.year) or (
|
||||
current.year == best_rec.year
|
||||
and current.month >= best_rec.month
|
||||
):
|
||||
best_rec = current
|
||||
|
||||
print(
|
||||
f"\nРезультат: {best_rec.duration} {best_rec.year} {best_rec.month}"
|
||||
)
|
||||
|
||||
except ValueError as e:
|
||||
print(f"Критическая ошибка: {e}")
|
||||
else:
|
||||
print("Неверный пункт меню.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_task_c4()
|
||||
|
||||
121
labPython/lab15/task_2.py
Normal file
121
labPython/lab15/task_2.py
Normal file
@@ -0,0 +1,121 @@
|
||||
import pickle
|
||||
import os
|
||||
import random
|
||||
|
||||
|
||||
class Student:
|
||||
def __init__(self, surname, name, grade, extra_data):
|
||||
self.surname = surname
|
||||
self.name = name
|
||||
self.grade = int(grade)
|
||||
self.extra_data = extra_data
|
||||
|
||||
def __str__(self):
|
||||
base = f"{self.surname:<15} | {self.name:<15} | {self.grade:<5} | "
|
||||
if self.grade == 1:
|
||||
return base + f"Скорость: {self.extra_data:<10}"
|
||||
elif self.grade == 4:
|
||||
return base + f"Балл аттест.: {self.extra_data:<10}"
|
||||
elif self.grade in [2, 3]:
|
||||
return base + f"Математика: {self.extra_data:<10}"
|
||||
return base
|
||||
|
||||
|
||||
def input_student():
|
||||
surname = input("Введите фамилию: ")
|
||||
name = input("Введите имя: ")
|
||||
while True:
|
||||
try:
|
||||
grade = int(input("Введите класс (1-4): "))
|
||||
if grade not in [1, 2, 3, 4]:
|
||||
raise ValueError
|
||||
break
|
||||
except ValueError:
|
||||
print("Ошибка: введите класс от 1 до 4.")
|
||||
|
||||
extra_data = None
|
||||
while True:
|
||||
try:
|
||||
if grade == 1:
|
||||
extra_data = int(input("Скорость чтения (слов/мин): "))
|
||||
elif grade == 4:
|
||||
extra_data = float(input("Балл аттестации (1-100): "))
|
||||
if not (1 <= extra_data <= 100):
|
||||
raise ValueError
|
||||
elif grade in [2, 3]:
|
||||
extra_data = float(input("Оценка по математике (1-10): "))
|
||||
if not (1 <= extra_data <= 10):
|
||||
raise ValueError
|
||||
break
|
||||
except ValueError:
|
||||
print("Некорректные данные для этого класса.")
|
||||
|
||||
return Student(surname, name, grade, extra_data)
|
||||
|
||||
|
||||
def save_to_binary(filename, students):
|
||||
with open(filename, "wb") as f:
|
||||
pickle.dump(students, f)
|
||||
|
||||
|
||||
def read_from_binary(filename):
|
||||
if not os.path.exists(filename):
|
||||
return []
|
||||
with open(filename, "rb") as f:
|
||||
return pickle.load(f)
|
||||
|
||||
|
||||
def run_task_2():
|
||||
filename = "students.bin"
|
||||
while True:
|
||||
print("\n--- Меню: Ученики (Бинарные файлы) ---")
|
||||
print("1. Ввести N учеников вручную и сохранить")
|
||||
print("2. Создать файл со случайными данными")
|
||||
print("3. Прочитать файл и вывести таблицу")
|
||||
print("0. Выход")
|
||||
|
||||
choice = input("Ваш выбор: ")
|
||||
|
||||
if choice == "0":
|
||||
break
|
||||
elif choice == "1":
|
||||
try:
|
||||
n = int(input("Введите N: "))
|
||||
students = [input_student() for _ in range(n)]
|
||||
save_to_binary(filename, students)
|
||||
except ValueError:
|
||||
print("Ошибка ввода числа.")
|
||||
elif choice == "2":
|
||||
surnames = ["Иванов", "Петров", "Сидоров", "Смирнов"]
|
||||
names = ["Алексей", "Мария", "Иван", "Анна"]
|
||||
random_students = []
|
||||
for _ in range(5):
|
||||
g = random.randint(1, 4)
|
||||
if g == 1:
|
||||
ex = random.randint(30, 100)
|
||||
elif g == 4:
|
||||
ex = round(random.uniform(50.0, 100.0), 1)
|
||||
else:
|
||||
ex = round(random.uniform(2.0, 10.0), 1)
|
||||
random_students.append(
|
||||
Student(random.choice(surnames), random.choice(names), g, ex)
|
||||
)
|
||||
save_to_binary(filename, random_students)
|
||||
print("Файл заполнен случайными данными.")
|
||||
elif choice == "3":
|
||||
data = read_from_binary(filename)
|
||||
if not data:
|
||||
print("Файл пуст или не существует.")
|
||||
else:
|
||||
print(
|
||||
f"\n{'Фамилия':<15} | {'Имя':<15} | {'Класс':<5} | Доп. информация"
|
||||
)
|
||||
print("-" * 60)
|
||||
for s in data:
|
||||
print(s)
|
||||
else:
|
||||
print("Неверный выбор.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_task_2()
|
||||
89
labPython/lab15/task_3.py
Normal file
89
labPython/lab15/task_3.py
Normal file
@@ -0,0 +1,89 @@
|
||||
class FitnessRecord:
|
||||
def __init__(self, duration, client_code, year, month):
|
||||
self.duration = duration
|
||||
self.client_code = client_code
|
||||
self.year = year
|
||||
self.month = month
|
||||
|
||||
|
||||
def solve():
|
||||
while True:
|
||||
print("\n--- Меню ExamTaskC16 ---")
|
||||
print("1. Ввести данные и выполнить расчет")
|
||||
print("2. Выход")
|
||||
|
||||
choice = input("Выберите вариант: ")
|
||||
|
||||
if choice == "2":
|
||||
break
|
||||
elif choice == "1":
|
||||
try:
|
||||
k_code = int(input("Введите код клиента K (10-99): "))
|
||||
n = int(input("Введите количество строк N: "))
|
||||
|
||||
records = []
|
||||
for i in range(n):
|
||||
print(f"Строка {i + 1} из {n}")
|
||||
line = input(
|
||||
"Формат <Продолжительность> <Код клиента> <Год> <Номер месяца>: "
|
||||
).split()
|
||||
|
||||
if len(line) != 4:
|
||||
print("Ошибка: должно быть 4 числа.")
|
||||
continue
|
||||
|
||||
dur, code, yr, mnth = map(int, line)
|
||||
records.append(FitnessRecord(dur, code, yr, mnth))
|
||||
|
||||
target_records = [r for r in records if r.client_code == k_code]
|
||||
|
||||
if not target_records:
|
||||
print("Нет данных")
|
||||
continue
|
||||
|
||||
years = {}
|
||||
for r in target_records:
|
||||
if r.duration == 0:
|
||||
continue
|
||||
if r.year not in years:
|
||||
years[r.year] = []
|
||||
years[r.year].append(r)
|
||||
|
||||
if not years:
|
||||
print("Нет данных")
|
||||
continue
|
||||
|
||||
results = []
|
||||
for year in years:
|
||||
year_records = years[year]
|
||||
|
||||
min_dur = min(r.duration for r in year_records)
|
||||
|
||||
candidates = [r for r in year_records if r.duration == min_dur]
|
||||
|
||||
best_month_record = max(candidates, key=lambda x: x.month)
|
||||
|
||||
results.append(
|
||||
{
|
||||
"duration": min_dur,
|
||||
"year": year,
|
||||
"month": best_month_record.month,
|
||||
}
|
||||
)
|
||||
|
||||
results.sort(key=lambda x: (x["duration"], x["year"]))
|
||||
|
||||
print("\nРезультат:")
|
||||
for res in results:
|
||||
print(f"{res['duration']} {res['year']} {res['month']}")
|
||||
|
||||
except ValueError:
|
||||
print("Ошибка: вводите только целые числа.")
|
||||
except Exception as e:
|
||||
print(f"Произошла ошибка: {e}")
|
||||
else:
|
||||
print("Неверный выбор.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
solve()
|
||||
Reference in New Issue
Block a user