Задача. Анализ курсов студентов
Реализуйте программу, которая:
- Читает файл
student_courses.json, содержащий:- имя студента,
- дату рождения (
birth_date) в форматедд.мм.гггг, - дату поступления (
enrollment_date) в том же формате, - список курсов.
- Вычисляет:
- общее количество студентов,
- средний возраст на момент поступления,
- количество студентов на каждом курсе.
- Сохраняет отчёт в
student_courses_report.json.
Пример входных данных
[
{"name": "Diana Williams", "birth_date": "12.06.1983", "enrollment_date": "29.04.2023", "courses": ["Physics", "Chemistry"]},
{"name": "Tina Miller", "birth_date": "06.07.2004", "enrollment_date": "18.04.2020", "courses": ["Biology", "Business"]}
]
Эталонное решение
# homework_58.py
import json
from datetime import datetime
from pathlib import Path
from collections import Counter
def parse_date(date_str: str) -> datetime:
return datetime.strptime(date_str, "%d.%m.%Y")
def calculate_age_at_enrollment(birth_date: str, enrollment_date: str) -> int:
birth = parse_date(birth_date)
enrollment = parse_date(enrollment_date)
age = enrollment.year - birth.year
if (enrollment.month, enrollment.day) < (birth.month, birth.day):
age -= 1
return age
def analyze_students(input_path: str = "student_courses.json",
output_path: str = "student_courses_report.json") -> None:
students = json.loads(Path(input_path).read_text(encoding="utf-8"))
total = len(students)
ages = [
calculate_age_at_enrollment(s["birth_date"], s["enrollment_date"])
for s in students
]
average_age = round(sum(ages) / total, 2) if total else 0
course_counts = Counter(
course for student in students for course in student["courses"]
)
report = {
"total_students": total,
"average_age_at_enrollment": average_age,
"course_counts": dict(course_counts),
}
Path(output_path).write_text(
json.dumps(report, ensure_ascii=False, indent=2),
encoding="utf-8"
)
print(f"Отчёт сохранён в {output_path}")
if __name__ == "__main__":
analyze_students()
Как проверить в VS Code
- Создайте
student_courses.jsonс тестовыми данными. - Создайте
homework_58.pyс решением. - Запустите:
python homework_58.py - Проверьте
student_courses_report.json.