7-6 宿舍谁最高? 分数 20 作者 张栋 单位 福州大学 学校选拔篮球队员,每间宿舍最多有 4 个人。现给出宿舍列表,请找出每个宿舍最高的同学。定义一个学生类 Student,有身高 height,体重 weight 等。
时间: 2024-05-13 18:13:29 浏览: 48
思路:首先需要定义一个学生类 Student,包含身高和体重两个属性。然后需要定义一个宿舍类 Dormitory,包含宿舍号、宿舍人数和宿舍成员列表等属性,以及获取宿舍最高同学的方法 getMaxStudent()。
接下来,遍历宿舍列表,对每个宿舍调用 getMaxStudent() 方法,得到最高同学的信息,并输出。
代码实现如下:
```
class Student:
def __init__(self, height, weight):
self.height = height
self.weight = weight
class Dormitory:
def __init__(self, number, count):
self.number = number
self.count = count
self.members = []
def addMember(self, student):
self.members.append(student)
def getMaxStudent(self):
max_height = 0
max_student = None
for student in self.members:
if student.height > max_height:
max_height = student.height
max_student = student
return max_student
# 测试数据
dorm_list = []
dorm1 = Dormitory(1, 3)
dorm1.addMember(Student(170, 60))
dorm1.addMember(Student(175, 62))
dorm1.addMember(Student(180, 65))
dorm_list.append(dorm1)
dorm2 = Dormitory(2, 2)
dorm2.addMember(Student(165, 55))
dorm2.addMember(Student(170, 58))
dorm_list.append(dorm2)
dorm3 = Dormitory(3, 4)
dorm3.addMember(Student(175, 65))
dorm3.addMember(Student(180, 68))
dorm3.addMember(Student(170, 62))
dorm3.addMember(Student(185, 70))
dorm_list.append(dorm3)
# 输出每个宿舍最高的同学
for dorm in dorm_list:
print("宿舍{}最高的同学身高为{}".format(dorm.number, dorm.getMaxStudent().height))
```
输出结果为:
```
宿舍1最高的同学身高为180
宿舍2最高的同学身高为170
宿舍3最高的同学身高为185
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![.pdf](https://img-home.csdnimg.cn/images/20210720083646.png)
![.pdf](https://img-home.csdnimg.cn/images/20210720083646.png)
![whl](https://img-home.csdnimg.cn/images/20210720083646.png)