以下是一个使用遗传算法生成每天每节课课程表并输出到Excel的Python代码示例:

import random
import numpy as np
import pandas as pd

# 定义问题参数
num_grades = 6  # 年级数量
num_teachers = 11  # 老师数量
num_days = 5  # 每周上课天数
num_periods = 7  # 每天上课节数
num_courses = 5  # 科目数量(不包括语数英和体育)

# 定义每个年级的科目和指定科目的课时量
grade_subjects = {
    1: {'语文': 5, '数学': 4, '英语': 3, '科学': 2, '社会': 2},
    2: {'语文': 5, '数学': 4, '英语': 3, '科学': 2, '社会': 2},
    3: {'语文': 5, '数学': 4, '英语': 3, '科学': 2, '社会': 2},
    4: {'语文': 5, '数学': 4, '英语': 3, '科学': 2, '社会': 2},
    5: {'语文': 5, '数学': 4, '英语': 3, '科学': 2, '社会': 2},
    6: {'语文': 5, '数学': 4, '英语': 3, '科学': 2, '社会': 2}
}

# 定义每个老师的指定课时量
teacher_courses = {
    1: {'语文': 4, '数学': 3, '英语': 3, '科学': 2, '社会': 2},
    2: {'语文': 4, '数学': 3, '英语': 3, '科学': 2, '社会': 2},
    3: {'语文': 4, '数学': 3, '英语': 3, '科学': 2, '社会': 2},
    4: {'语文': 4, '数学': 3, '英语': 3, '科学': 2, '社会': 2},
    5: {'语文': 4, '数学': 3, '英语': 3, '科学': 2, '社会': 2},
    6: {'语文': 4, '数学': 3, '英语': 3, '科学': 2, '社会': 2},
    7: {'语文': 4, '数学': 3, '英语': 3, '科学': 2, '社会': 2},
    8: {'语文': 4, '数学': 3, '英语': 3, '科学': 2, '社会': 2},
    9: {'语文': 4, '数学': 3, '英语': 3, '科学': 2, '社会': 2},
    10: {'语文': 4, '数学': 3, '英语': 3, '科学': 2, '社会': 2},
    11: {'语文': 4, '数学': 3, '英语': 3, '科学': 2, '社会': 2}
}

# 定义遗传算法参数
population_size = 100  # 种群大小
mutation_rate = 0.01  # 变异率
num_generations = 100  # 迭代次数

# 生成初始种群
def generate_population():
    population = []
    for _ in range(population_size):
        chromosome = []
        for _ in range(num_days * num_periods):
            gene = random.randint(0, num_courses + 1)  # 0表示休息,1-5表示科目
            chromosome.append(gene)
        population.append(chromosome)
    return population

# 计算适应度
def calculate_fitness(chromosome):
    conflicts = 0
    schedule = np.array(chromosome).reshape(num_days, num_periods)
    
    # 检查每天每节课的冲突
    for day in range(num_days):
        for period in range(num_periods):
            course = schedule[day][period]
            
            # 检查是否在前3节课里排了语数英
            if period < 3 and (course == 1 or course == 2 or course == 3):
                conflicts += 1
            
            # 检查是否在前3节课里排了体育
            if period < 3 and course == num_courses + 1:
                conflicts += 1
    
    # 检查每个年级各科目的课时量是否满足要求
    for grade in range(1, num_grades + 1):
        grade_schedule = schedule[:, grade-1]
        grade_subject_hours = sum([grade_subjects[grade][subject] for subject in grade_subjects[grade]])
        for subject in grade_subjects[grade]:
            subject_hours = sum(grade_schedule == subject)
            if subject_hours != grade_subjects[grade][subject]:
                conflicts += abs(subject_hours - grade_subjects[grade][subject])
    
    # 检查每个老师的指定课时量是否满足要求
    for teacher in range(1, num_teachers + 1):
        teacher_schedule = schedule[:, teacher-1]
        for subject in teacher_courses[teacher]:
            subject_hours = sum(teacher_schedule == subject)
            if subject_hours != teacher_courses[teacher][subject]:
                conflicts += abs(subject_hours - teacher_courses[teacher][subject])
    
    fitness = 1 / (conflicts + 1)
    return fitness

# 选择操作
def selection(population, fitness_scores):
    selected_indices = np.random.choice(range(population_size), size=population_size, p=fitness_scores/sum(fitness_scores))
    selected_population = [population[i] for i in selected_indices]
    return selected_population

# 交叉操作
def crossover(parent1, parent2):
    crossover_point = random.randint(1, num_days * num_periods - 1)
    child1 = parent1[:crossover_point] + parent2[crossover_point:]
    child2 = parent2[:crossover_point] + parent1[crossover_point:]
    return child1, child2

# 变异操作
def mutate(chromosome):
    for i in range(num_days * num_periods):
        if random.random() < mutation_rate:
            chromosome[i] = random.randint(0, num_courses + 1)
    return chromosome

# 创建课程表
def create_schedule():
    population = generate_population()
    
    for generation in range(num_generations):
        fitness_scores = [calculate_fitness(chromosome) for chromosome in population]
        selected_population = selection(population, fitness_scores)
        
        next_population = []
        while len(next_population) < population_size:
            parent1, parent2 = random.choices(selected_population, k=2)
            child1, child2 = crossover(parent1, parent2)
            next_population.extend([mutate(child1), mutate(child2)])
        
        population = next_population
    
    best_chromosome = max(population, key=calculate_fitness)
    best_schedule = np.array(best_chromosome).reshape(num_days, num_periods)
    
    return best_schedule

# 输出课程表到Excel
def output_schedule(schedule):
    days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
    periods = [f'Period {i+1}' for i in range(num_periods)]
    
    df = pd.DataFrame(schedule, index=days, columns=periods)
    writer = pd.ExcelWriter('schedule.xlsx')
    df.to_excel(writer, sheet_name='Schedule')
    writer.save()

# 主函数
def main():
    schedule = create_schedule()
    output_schedule(schedule)

if __name__ == '__main__':
    main()

请注意,这只是一个示例代码,可能需要根据实际需求进行进一步修改和完善


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

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