定义学生类,包括学号、姓名、性别、多门课程的成绩;假设有n个学生,由键盘输入 学生信息; 定义类成员函数,计算每个学生的平均成绩; 按课程统计每门课程的平均成绩、最高分和最低分; 按平均分对所有学生进行排名同时按名次输出所有学生信息; 通过输入学生学号或姓名查询某学生的信息。
时间: 2023-12-16 14:11:47 浏览: 65
class Student:
def __init__(self, id, name, gender, scores):
self.id = id
self.name = name
self.gender = gender
self.scores = scores
def average_score(self):
return sum(self.scores)/len(self.scores)
class ScoreSystem:
def __init__(self, students):
self.students = students
def course_stats(self):
stats = {}
for student in self.students:
for i, score in enumerate(student.scores):
if i not in stats:
stats[i] = {'sum': score, 'count': 1, 'max': score, 'min': score}
else:
stats[i]['sum'] += score
stats[i]['count'] += 1
stats[i]['max'] = max(stats[i]['max'], score)
stats[i]['min'] = min(stats[i]['min'], score)
return stats
def rank_students(self):
self.students.sort(key=lambda x: x.average_score(), reverse=True)
for i, student in enumerate(self.students):
student.rank = i+1
def search_student(self, keyword):
for student in self.students:
if student.id == keyword or student.name == keyword:
return student
return None
# example usage
n = int(input("How many students? "))
students = []
for i in range(n):
id = input("Student ID: ")
name = input("Student name: ")
gender = input("Student gender: ")
scores = [int(x) for x in input("Student scores (separated by space): ").split()]
student = Student(id, name, gender, scores)
students.append(student)
score_system = ScoreSystem(students)
course_stats = score_system.course_stats()
score_system.rank_students()
print("Course stats:")
for i, stat in course_stats.items():
print("Course", i+1, "average:", stat['sum']/stat['count'], "max:", stat['max'], "min:", stat['min'])
print("\nStudent ranking:")
for student in students:
print(student.rank, student.id, student.name, student.gender, student.average_score())
keyword = input("\nEnter student ID or name to search: ")
result = score_system.search_student(keyword)
if result:
print("Student found:", result.id, result.name, result.gender, result.scores)
else:
print("Student not found.")
阅读全文