Search code examples
pythonarrayslistnotation

python array notation shorthand :"k%parents.shape[0]" mean?


I came across this notation today as going through this tutorial here:https://towardsdatascience.com/genetic-algorithm-implementation-in-python-5ab67bb124a6

parent1_idx = k%parents.shape[0]

what is the right-hand side going to return? and what is the name for this kind of expression? thanks in advance !


Solution

  • I see that line in this snippet of code from the mentioned article:

    for k in range(offspring_size[0]):
         # Index of the first parent to mate.
         parent1_idx = k%parents.shape[0]
         # Index of the second parent to mate.
         parent2_idx = (k+1)%parents.shape[0]
    

    Where parents is defined as follows:

    parents = numpy.empty((num_parents, pop.shape[1]))
    for parent_num in range(num_parents):
        max_fitness_idx = numpy.where(fitness == numpy.max(fitness))
        max_fitness_idx = max_fitness_idx[0][0]
        parents[parent_num, :] = pop[max_fitness_idx, :]
        fitness[max_fitness_idx] = -99999999999
    return parents
    

    From the above two lines, it's quite evident that both k and parents.shape[0] are integers, and hence the line is a simple modulo operator between two numerical variables: a = b % c .