我是遗传算法的新手,前几天做了一个重新创建目标字符串的算法。所以我试着做一个可以做一个魔方的。没关系,直到我进入交叉部分,意识到我不能只做一个单点交叉。所以我尝试执行部分映射的交叉,但我不能也仍然不能让它工作。我了解部分映射的交叉是如何工作的,我只是无法将它实现到 python 中。由于我的代码尚未完成,我将交叉函数隔离在不同的程序中并对其进行了更改,因此父母是一个固定列表。
有人可以更正我的代码,或者如果它完全错误,请告诉我如何在整数 1 到 9 的 2 个列表上执行部分映射交叉?另外,我很抱歉并理解我对变量的命名不是那么好,但我只是想让程序能够进行不断的编辑。
import random
parent1 = [1,2,3,4,5,6,7,8,9]
parent2 = [5,4,6,7,2,1,3,9,8]
firstCrossPoint = random.randint(0,len(parent1)-1) #Creating parameters for random sublist
secondCrossPoint = random.randint(firstCrossPoint+1,len(parent1))
parent1MiddleCross = parent1[firstCrossPoint:secondCrossPoint]
parent2MiddleCross = parent2[firstCrossPoint:secondCrossPoint]
child1 = (parent1[:firstCrossPoint] + parent2MiddleCross + parent1[secondCrossPoint:])
child2 = (parent2[:firstCrossPoint] + parent1MiddleCross + parent2[secondCrossPoint:])
relationsWithDupes = []
for i in range(len(parent1MiddleCross)):
relationsWithDupes.append([parent2MiddleCross[i], parent1MiddleCross[i]])
relations = []
for pair in relationsWithDupes:
for i in range(len(relationsWithDupes)):
if pair[0] in relationsWithDupes[i] or pair[1] in relationsWithDupes[i]:
if pair != relationsWithDupes[i]:
if pair[0] == relationsWithDupes[i][1]:
pair[0] = relationsWithDupes[i][0]
else:
pair[1] = relationsWithDupes[i][1]
if pair not in relations and pair[::-1] not in relations:
relations.append(pair)
for i in child1[:firstCrossPoint]:
for x in relations:
if i == x[0]:
i = x[1]
for i in child1[secondCrossPoint:]:
for x in relations:
if i == x[0]:
i = x[1]
for i in child2[:firstCrossPoint]:
for x in relations:
if i == x[1]:
i = x[0]
for i in child2[secondCrossPoint:]:
for x in relations:
if i == x[1]:
i = x[0]
print(child1)
print(child2)