우수 학생
Coddy Python 여정의 Logic & Flow 섹션에 포함된 레슨 — 78개 중 45번째.
챌린지
쉬움하나의 인자 threshold (float)를 받는 filter_top_students라는 이름의 함수를 만드세요. 이 함수는 다음을 수행해야 합니다:
student_records딕셔너리를 반복하여 평균 성적이 지정된threshold보다 높은 모든 학생을 찾습니다.- 각 학생의 평균 성적을 구하기 위해
calculate_average_grade함수를 사용합니다. - 상위 학생들의 이름 리스트를 반환합니다.
- 기준을 충족하는 학생이 없으면 빈 리스트를 반환합니다.
코드의 맨 아래에 다음 코드 블록을 추가(교체)하세요:
add_student("Alice", 20, ["Math", "Physics"])
add_student("Bob", 22, ["Math", "Biology"])
add_student("Diana", 23, ["Chemistry", "Physics"])
add_grade("Alice", 90)
add_grade("Alice", 85)
add_grade("Bob", 75)
add_grade("Diana", 95)
print(filter_top_students(80)) # Should return ["Alice", "Diana"]
print(filter_top_students(90)) # Should return ["Diana"]
print(filter_top_students(100)) # Should return an empty list딕셔너리, 세트, 그리고 의사 결정을 결합하여 어떻게 완전히 기능하는 프로그램을 만들었는지 잠시 되새겨 보세요. 잘하셨습니다! 🚀
직접 해보기
student_records = {}
def add_student(name, age, courses):
if name in student_records:
print(f"Student '{name}' already exists.")
return
student_records[name] = {"age": age, "grades": set(), "courses": set(courses)}
print(f"Student '{name}' added successfully.")
def add_grade(name, grade):
if name not in student_records:
print(f"Student '{name}' not found.")
return
student_records[name]["grades"].add(grade)
print(f"Grade {grade} added for student '{name}'.")
def is_enrolled(name, course):
if name not in student_records:
print(f"Student '{name}' not found.")
return False
return course in student_records[name]["courses"]
def calculate_average_grade(name):
if name not in student_records:
print(f"Student '{name}' not found.")
return None
grades = student_records[name]["grades"]
if not grades:
return 0
return sum(grades) / len(grades)
def list_students_by_course(course):
students_in_course = []
for name, details in student_records.items():
if course in details["courses"]:
students_in_course.append(name)
return students_in_course
add_student("Alice", 20, ["Math", "Physics"])
add_student("Bob", 22, ["Math", "Biology"])
add_student("Diana", 23, ["Chemistry", "Physics"])
print(list_students_by_course("Math")) # Should return ["Alice", "Bob"]
print(list_students_by_course("Physics")) # Should return ["Alice", "Diana"]
print(list_students_by_course("Biology")) # Should return ["Bob"]
print(list_students_by_course("History")) # Should return an empty list