crossover.py 文件源码

python
阅读 25 收藏 0 点赞 0 评论 0

项目:levis 作者: rawg 项目源码 文件源码
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]
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号