2、如果N不是n的整数倍,则n个小组中的人数会不相同。以上就是50个人败拦在python程序随机分组的方法。
可以大桐侍段尝试使用k-means clustering:
import scipy.cluster.vq as vq
import collections
import numpy as np
def auto_cluster(data,threshold=0.1,k=1):
# There are more sophisticated ways of determining k
# See http://en.wikipedia.org/wiki/Determining_the_number_of_clusters_in_a_data_set
data=np.asarray(data)
distortion=1e20
while distortion>threshold:
codebook,distortion=vq.kmeans(data,k)
k+=1
code,dist=vq.vq(data,codebook)
groups=collections.defaultdict(list)
for index,datum in zip(code,data):
groups[index].append(datum)
return groups
np.random.seed(784789)
N=20
weights=100*np.random.random(N)
groups=auto_cluster(weights,threshold=1.5,k=N//5)
for index,data in enumerate(sorted(groups.values(),key=lambda d: np.mean(d))):
print('滚谈坦{i}: {d}'.format(i=index,d=data))
上面的代码生成N个权重的随机序列.
# teachers=['a','b','c','d','e','f','g','h','j','k','m']# offices=[[],[],[],[]]
# 要求是将11名老师随机分配到4个办公室,每个办公室保证至少分配两名老师。
import random
teachers = ['a','b','c','d','e','f','g','h','j','k','m']
offices = [[],[],[],[]]
class Office:
def __init__(self, num):
self.teachers_list = []
self.num = num
def add(self, x):
self.teachers_list.append(x)
def ret(self):
return self.teachers_list
def __str__(self):
return str(self.num)
# 调用系统时间,实现随机数
random.seed()
# 一共3种情况:
# 3 3 3 2 = 11
# 4 2 3 2 = 11
# 5 2 2 2 = 11
case_index = random.randrange(1, 4)
offices_list = []
if case_index == 1:
# 3 3 3 2
for e in [3,3,3,2]:
offices_list.append(Office(e))
elif case_index == 2:
# 4 2 3 2
for e in [4,3,2,2]:
offices_list.append(Office(e))
else:
# 5 2 2 2
旁团for e in [5,2,2,2]:
offices_list.append(Office(e))
# 打乱顺序
random.shuffle(offices_list)
print("办公室随机分配名额如下:")
for office in offices_list:
print(office, end="洞梁 ")
print()
print("开始分配老师:")
# 分配老师
for teacher in teachers:
while True:
index = random.randrange(0, len(offices))
office = offices_list[index]
if len(office.teachers_list) >= office.num:
continue
office.add(teacher)
break
for i in range(len(offices_list)):
office = offices_list[i]
运颤橘 offices[i] = office.ret()
print(offices[i])
可以运行!请指教!
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)