以下是使用pandas输出Excel的Python代码,实现小学老师排课的遗传算法:

import pandas as pd
import random

# 定义常量
WEEKDAYS = 5
LESSONS_PER_DAY = 7
SUBJECTS = ['语文', '数学', '英语', '体育']
NUM_TEACHERS = 11
NUM_GRADES = 6
NUM_CLASSES = {'一年级': 1, '二年级': 2, '三年级': 1, '四年级': 1, '五年级': 1, '六年级': 1}

# 创建空的排课表
timetable = pd.DataFrame(index=range(WEEKDAYS * LESSONS_PER_DAY),
                         columns=['星期', '节次', '年级', '班级', '老师', '课程'])

# 定义遗传算法的相关函数
def generate_chromosome():
    # 随机生成一个染色体
    chromosome = []
    for day in range(WEEKDAYS):
        for lesson in range(LESSONS_PER_DAY):
            grade = random.choice(list(NUM_CLASSES.keys()))
            if grade == '二年级' and lesson < 3:
                # 二年级只有2个班且不排1-3节
                continue
            teacher = random.randint(1, NUM_TEACHERS)
            subject = random.choice(SUBJECTS)
            
            chromosome.append([day, lesson, grade, NUM_CLASSES[grade], teacher, subject])
    
    return chromosome

def fitness(chromosome):
    # 计算染色体的适应度
    score = 0
    for i in range(len(chromosome)):
        for j in range(i+1, len(chromosome)):
            if chromosome[i][2] == chromosome[j][2] and chromosome[i][4] == chromosome[j][4]:
                # 同一课程不连续上课
                score -= 1
            if chromosome[i][0] == chromosome[j][0] and chromosome[i][1] == chromosome[j][1] and chromosome[i][4] == chromosome[j][4]:
                # 同一课程每天不能出现3次
                score -= 1
    
    return score

def crossover(parent1, parent2):
    # 实现染色体的交叉
    point = random.randint(1, len(parent1) - 1)
    child1 = parent1[:point] + parent2[point:]
    child2 = parent2[:point] + parent1[point:]
    
    return child1, child2

def mutation(chromosome, mutation_rate):
    # 实现染色体的变异
    for i in range(len(chromosome)):
        if random.random() < mutation_rate:
            chromosome[i][2] = random.choice(list(NUM_CLASSES.keys()))
            chromosome[i][3] = NUM_CLASSES[chromosome[i][2]]
            chromosome[i][4] = random.randint(1, NUM_TEACHERS)
            chromosome[i][5] = random.choice(SUBJECTS)
    
    return chromosome

def genetic_algorithm(population_size, mutation_rate, generations):
    # 遗传算法主函数
    population = []
    for _ in range(population_size):
        chromosome = generate_chromosome()
        population.append(chromosome)
    
    for _ in range(generations):
        scores = []
        for chromosome in population:
            score = fitness(chromosome)
            scores.append(score)
        
        # 选择适应度较高的染色体作为父代
        parent1 = population[scores.index(max(scores))]
        parent2 = population[scores.index(sorted(scores)[-2])]
        
        # 交叉和变异
        child1, child2 = crossover(parent1, parent2)
        child1 = mutation(child1, mutation_rate)
        child2 = mutation(child2, mutation_rate)
        
        # 替换原来的染色体
        population[scores.index(min(scores))] = child1
        population[scores.index(sorted(scores)[-2])] = child2
    
    return population[scores.index(max(scores))]

# 运行遗传算法
best_chromosome = genetic_algorithm(population_size=100, mutation_rate=0.1, generations=100)

# 将排课结果写入Excel
for i in range(len(best_chromosome)):
    timetable.loc[i, '星期'] = best_chromosome[i][0] + 1
    timetable.loc[i, '节次'] = best_chromosome[i][1] + 1
    timetable.loc[i, '年级'] = best_chromosome[i][2]
    timetable.loc[i, '班级'] = best_chromosome[i][3]
    timetable.loc[i, '老师'] = best_chromosome[i][4]
    timetable.loc[i, '课程'] = best_chromosome[i][5]

timetable.to_excel('timetable.xlsx', index=False)

这段代码使用pandas库创建一个空的排课表,并定义了遗传算法的各个函数。然后,通过调用genetic_algorithm函数来运行遗传算法,得到最优的排课结果。

最后,将排课结果写入Excel文件timetable.xlsx

小学教师排课遗传算法Python代码:使用pandas输出Excel

原文地址: https://www.cveoy.top/t/topic/qos7 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录