1

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 !

C Lu
  • 87
  • 8
  • 2
    What are you confused about? It is modulo operator. So, it is `k % ` – kuro Oct 29 '18 at 08:57
  • presumably `shape` is some sort of indexed attribute of `parents` (i.e. `parents.shape` gets you a list (or something) which you can pull a `[0]` index from). I'm not sure about the k%, though I have seen `%`, IIRC, in string formatting (https://www.learnpython.org/en/String_Formatting). If k is a variable, the % is probably a modulo. – NotAnAmbiTurner Oct 29 '18 at 08:58

2 Answers2

1

% is a operator in python, i-e Modulus operator - it gives remainder of the division of left operand by the right

Oli
  • 1,313
  • 14
  • 31
1

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 .

darthbhyrava
  • 505
  • 4
  • 14