python -20-老师随机分配办公室
作者:
hsiaojun | 来源:发表于
2018-04-19 01:29 被阅读0次"""
老师分配办公室的应用练习
输入办公室个数
输入老师的个数
然后将了老师分配到办公室,保证每个办公室至少一个
"""
import random
room_nums = 0
teacher_nums = 0
while True:
r_nums = input("请输入教室的个数:")
t_nums = input("请输入老师的数量:")
if int(t_nums) > int(r_nums):
room_nums = int(r_nums)
teacher_nums = int(t_nums)
break
else:
print("老师的数量少于教室数量,请重新输入")
# 创建办公室列表,即创建一个嵌套列表
rooms = []
while room_nums >= 1:
rooms.append([])
room_nums -= 1
# 创建老师列表,并添加老师
teachers = []
while teacher_nums >= 1:
teacher_nums -= 1
teachers.append("teacher%d" % (teacher_nums + 1))
# 开始安排办公室
# 1.先随机选出三位老师,依次放到办公室中
for room in rooms:
# 随机选出一名老师,注意teachers长度会变
index = random.randint(0, len(teachers) - 1)
# pop方法弹出一个元素,并列表中删除
teac = teachers.pop(index)
room.append(teac)
# 2.将剩下的老师,再随机分配
for teacher in teachers:
room_index = random.randint(0, len(rooms) - 1)
rooms[room_index].append(teacher)
print("分配结束后: ", rooms)
本文标题:python -20-老师随机分配办公室
本文链接:https://www.haomeiwen.com/subject/ecdikftx.html
网友评论