Menu
Coddy logo textTech

Recapitulação - Sistema de Registro de Alunos

Parte da seção Object Oriented Programming do Journey de Python da Coddy. Lição 32 de 64.

challenge icon

Desafio

Médio

Neste desafio, você implementará um sistema completo de gerenciamento de registros de alunos.

Você precisa editar dois arquivos para completar este desafio:

  • student.py - Implemente a classe Student com o encapsulamento adequado
  • studentregistry.py - Implemente a classe StudentRegistry para gerenciar os alunos

Siga os comentários TODO detalhados em cada arquivo para orientação passo a passo. Sua implementação será testada em relação a casos de teste abrangentes que verificam:

  • Validação de atributos e tratamento de erros adequados
  • Cálculo correto das médias de notas
  • Funcionalidade do registro com vários cenários de alunos
  • Condições de limite e casos de borda

Experimente você mesmo

from student import Student
from studentregistry import StudentRegistry
import time
import random

# Manipulador de casos de teste para testes abrangentes
test_case = input()

if test_case == "default_test":
    # Criar estudantes
    student1 = Student(1001, "Alice Smith")
    student2 = Student(1002, "Bob Johnson")
    student3 = Student(1003, "Charlie Brown")

    # Adicionar notas
    student1.add_grade("Math", 90)
    student1.add_grade("Science", 85)
    student1.add_grade("English", 92)

    student2.add_grade("Math", 78)
    student2.add_grade("Science", 80)
    student2.add_grade("English", 85)

    student3.add_grade("Math", 95)
    student3.add_grade("Science", 91)
    student3.add_grade("English", 89)

    # Exibir registros dos estudantes
    print("Student Records:")
    student1.display_record()
    print()
    student2.display_record()
    print()
    student3.display_record()
    print()

    # Testar validação de nome
    try:
        student1.name = "J"  # Muito curto
    except ValueError as e:
        print(f"Name validation error: {e}")
    print()

    # Criar registro e adicionar estudantes
    registry = StudentRegistry()
    registry.add_student(student1)
    registry.add_student(student2)
    registry.add_student(student3)

    # Exibir todos os estudantes
    print("All Students in Registry:")
    registry.display_all()
    print()

    # Obter o melhor estudante
    top_student = registry.get_top_student()
    print(f"Top Student: {top_student.name} (Average: {top_student.grade_average})")

    # Remover um estudante
    registry.remove_student(1002)  # Remover Bob
    print("\
After removing student 1002:")
    registry.display_all()

elif test_case == "empty_registry":
    # Testar um registro vazio
    registry = StudentRegistry()
    top_student = registry.get_top_student()
    if top_student is None:
        print("Top student in empty registry: None")
    print("Displaying all students in empty registry:")
    registry.display_all()  # Não deve exibir nada

elif test_case == "validation_tests":
    # Testar todas as regras de validação
    student = Student(1001, "Valid Name")
    print(f"Created student with name: {student.name}")
    
    # Testar nome vazio
    try:
        student.name = ""
    except ValueError as e:
        print(f"Empty name test: {e}")
    
    # Testar nome com apenas um caractere
    try:
        student.name = "A"
    except ValueError as e:
        print(f"Single character name test: {e}")
    
    # Testar valor de matrícula não booleano
    try:
        student.enrolled = "yes"
    except ValueError as e:
        print(f"Non-boolean enrolled test: {e}")
    
    # Testar alterações válidas
    student.name = "New Valid Name"
    student.enrolled = False
    print(f"After valid changes - Name: {student.name}, Enrolled: {student.enrolled}")

elif test_case == "grade_calculation":
    # Testar cálculo da média de notas
    student = Student(1001, "Test Student")
    print(f"Student with no grades - Average: {student.grade_average}")
    
    # Adicionar uma nota
    student.add_grade("Math", 85)
    print(f"Student with one grade - Average: {student.grade_average}")
    
    # Adicionar mais notas
    student.add_grade("Science", 90)
    student.add_grade("English", 95)
    print(f"Student with multiple grades - Average: {student.grade_average}")

elif test_case == "registry_operations":
    # Testar todas as operações de registro
    registry = StudentRegistry()
    
    # Criar estudantes
    student1 = Student(101, "Student One")
    student2 = Student(102, "Student Two")
    
    # Adicionar estudantes
    registry.add_student(student1)
    registry.add_student(student2)
    print("After adding students:")
    registry.display_all()
    
    # Obter estudante
    retrieved_student = registry.get_student(101)
    print(f"\
Retrieved student 101: {retrieved_student.name if retrieved_student else None}")
    
    # Obter estudante inexistente
    non_existent = registry.get_student(999)
    print(f"Retrieved student 999: {non_existent}")
    
    # Remover estudante
    registry.remove_student(101)
    print("\
After removing student 101:")
    registry.display_all()
    
    # Remover estudante inexistente (não deve gerar erro)
    registry.remove_student(999)
    print("\
After attempting to remove non-existent student 999:")
    registry.display_all()

elif test_case == "large_registry":
    # Testar desempenho com muitos estudantes
    start_time = time.time()
    registry = StudentRegistry()
    
    # Criar 100 estudantes com notas aleatórias
    for i in range(1, 101):
        student = Student(1000 + i, f"Student {i}")
        # Adicionar 5 notas aleatórias
        for j in range(5):
            student.add_grade(f"Course {j+1}", random.randint(60, 100))
        registry.add_student(student)
    
    creation_time = time.time() - start_time
    print(f"Time to create 100 students: {creation_time:.4f} seconds")
    
    # Encontrar o melhor estudante
    start_time = time.time()
    top_student = registry.get_top_student()
    top_time = time.time() - start_time
    print(f"Time to find top student: {top_time:.4f} seconds")
    print(f"Top student: {top_student.name} with average {top_student.grade_average:.2f}")
    
    # Encontrar os 5 melhores estudantes manualmente
    print("\
Top 5 students:")
    students_list = []
    for i in range(1, 101):
        student = registry.get_student(1000 + i)
        students_list.append(student)
    
    # Ordenar pela média de notas em ordem decrescente
    students_list.sort(key=lambda s: s.grade_average, reverse=True)
    
    # Exibir os 5 melhores
    for i in range(5):
        student = students_list[i]
        print(f"{i+1}. {student.name}: {student.grade_average:.2f}")

Todas as lições de Object Oriented Programming

Pratique por conta própria: Compilador de Python online