用Python 写一个基于遗传算法的排班代码
时间: 2023-02-22 21:32:56 浏览: 327
遗传算法是一种仿生学算法,常被用于求解最优化问题。
下面是一个基于遗传算法的排班代码示例:
```
import random
import numpy as np
def create_schedule(n_employees, n_shifts):
# 随机创建初始排班表
schedule = np.random.randint(0, n_employees, (n_shifts,))
return schedule
def evaluate_schedule(schedule, preferences):
# 评估排班表的适应性
fitness = 0
for i, shift in enumerate(schedule):
fitness += preferences[shift][i]
return fitness
def mutate_schedule(schedule, n_employees):
# 随机改变一个员工的排班
i = random.randint(0, len(schedule) - 1)
schedule[i] = random.randint(0, n_employees - 1)
return schedule
def genetic_algorithm(preferences, n_employees, n_shifts, n_generations):
# 遗传算法主体
schedules = [create_schedule(n_employees, n_shifts) for i in range(100)]
for i in range(n_generations):
schedules = [mutate_schedule(s, n_employees) for s in schedules]
schedules = [(s, evaluate_schedule(s, preferences)) for s in schedules]
schedules.sort(key=lambda x: x[1], reverse=True)
schedules = schedules[:50]
return schedules[0][0]
# 示例:假设有10个员工,7天排班
preferences = [[random.randint(0, 100) for i in range(7)] for j in range(10)]
schedule = genetic_algorithm(preferences, 10, 7, 100)
print(schedule)
```
该代码的工作原理是:首先随机生成一组排班表,然后在这组排班表上进行多代的进化,每一代中对排班表进行随机变异,再评估每一种排班表的适应性,最终选出适应性最高的排
阅读全文