交叉过程即存在于上图的”交叉“(crossover)步骤中。
随机地选择1个交叉位点进行交叉,如下图所示:
用random库实现随机性:
import random # 简单的单点交叉方式 def sing_muta(list1, list2): # 假设len(list1) == len(list2) # 随机选择交叉点 cross_pt = random.randint(0, len(list1) - 2) list1_cut = list1[cross_pt + 1: len(list1)] list2_cut = list2[cross_pt + 1: len(list2)] new_list1 = list1[0: cross_pt + 1] new_list1.append(list2_cut) new_list2 = list2[0: cross_pt + 1] new_list2.append(list1_cut) return new_list1, new_list2 list1 = [1, 2, 3, 4, 5, 6, 7, 8] list2 = [10, 20, 30, 40, 50, 60, 70, 80] for i in range(5): print(sing_muta(list1, list2))
'运行
程序输出(5次交换结果):
随机地选择一个交叉起点和一个交叉终点,交换父代两个基因的中间部分,如下图所示:
Python代码:
import random # 简单的两点交叉方式 def doub_muta(list1, list2): # 假设len(list1) == len(list2) # 随机选择起点和终点 new_list1 = list1 new_list2 = list2 cross_begin = random.randint(0, len(list1) - 1) cross_end = random.randint(0, len(list1) - 1) if cross_begin == cross_end: cross_end += 1 # 至少产生1个位点的交换 elif cross_begin > cross_end: cross_begin, cross_end = cross_end, cross_begin # 结束位点不能在开始位点之前 print(cross_begin, cross_end) # 检查位点 # 切出片段 list1_cut = new_list1[cross_begin: cross_end] list2_cut = new_list2[cross_begin: cross_end] new_list1[cross_begin: cross_end] = list2_cut new_list2[cross_begin: cross_end] = list1_cut return new_list1, new_list2 for i in range(5): list1 = [1, 2, 3, 4, 5, 6, 7, 8] list2 = [10, 20, 30, 40, 50, 60, 70, 80] print(doub_muta(list1, list2))
'运行
程序输出(5次交换结果):