uniform crossover(均匀交叉),遗传算法(Genetic Algorithm,GA),python
假设有双亲p1和p2的二进制基因染色体表达,子代的基因以等概率(50%)来自双亲中之一,如图:
import random
# 双亲染色体
p1 = [1, 0, 0, 1, 1]
p2 = [0, 0, 1, 1, 0]
def uniform_crossover():
c = [] # 子代
for i in range(len(p1)):
r = random.randint(1, 2) # 等概率产生1和2
if r == 1: # 如果是1,则取p1[i]
c.append(p1[i])
if r == 2: # 如果是2,则取p2[i]
c.append(p2[i])
print(c)
if __name__ == '__main__':
for i in range(10):
uniform_crossover()
运行输出: