def single_point_bin(parent1, parent2, length=None, locus=None):
"""Return a new chromosome through a single-point crossover.
This is suitable for use with binary encoding.
Args:
parent1 (List): A parent chromosome.
parent2 (List): A parent chromosome.
locus (int): The crossover point or ``None`` to choose one at random.
If ``None``, then ``length`` must be the number of bits used in the
parent chromosomes.
length(int): The number of bits used. Not used if a locus is provided.
Returns:
List[int]: Two new chromosomes descended from the given parents.
Raises:
ValueError: if neither ``locus`` or ``length`` is specified.
"""
if locus is None and length is None:
raise ValueError("Either the length or a locus is required.")
if locus is None:
locus = int(random.triangular(1, length / 2, length - 2))
if length is None:
length = 2 * locus
maskr = 2 ** locus - 1
maskl = (2 ** length - 1) & ~maskr
child1 = parent1 & maskl | parent2 & maskr
child2 = parent2 & maskl | parent1 & maskr
return [child1, child2]
评论列表
文章目录