Python basics listening notes

#Requirements: Randomly assign offices to 8 teachers

#First define a list to store the names of 8
teachers teachers = ['xiaowang', 'xiaoli', 'xiangming', 'xiaohua', 'xiaogang', 'lili', 'huyu', 'wuyu']

#Define an empty nested list with three empty lists to wait for other teachers to join
office = [[],[],[]]

#Randomly assign offices to 8 teachers: the way to generate random numbers
for teacher in teachers:
index = random.randint(0,2)
office[index].append(teacher)
# print(office)

#Print out the teachers in each office and display the office number
i = 1
for room in office:
#print(room)
print("The teacher in office %d is "%i)
for name in room:
print(name )

print("-"*10)
i+=1

 

 

#Extension: How to ensure that there are at least two people in each office?
import random #First
define a list to store the names of 8
teachers teachers = ['xiaowang', 'xiaoli', 'xiangming', 'xiaohua', 'xiaogang', 'lili', 'huyu', 'wuyu']

#Define an empty nested list with three empty lists to wait for other teachers to join
office = [[],[],[]]

#Get the length of the empty list, which is the number of offices
listLength = len(office)

#First randomly assign two teachers to each of the three offices
for room in range(0,listLength):
i = 0
while i<2: #Randomly assign two teachers to each office
length = len(teachers)- 1
teacherIndex = random.randint(0,length) #Generate a random number between 0 and 7
teacher = teachers[teacherIndex] #Randomly select a teacher
office[room].append(teacher) #Add the selected teacher to the office Del teachers[teacherIndex] in the office with the number room

#delete the selected teacher from the list
i+=1

#Randomly assign the remaining two teachers to three offices, these two may be assigned to the same office
for j in range(0,2):
index = random.randint(0,2)
rest_teacher = teachers[ j]
office[index].append(rest_teacher)

j+=1 #Print

out the teachers in each office and display the office number
k = 1
for roomNum in office:
print("The teacher in office %d is:"% k)
for name in roomNum:
print(name)

print("-"*10)
k+=1

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324985202&siteId=291194637