我今天遇到这种表示法
本教程在这里:https://towardsdatascience.com/genetic-algorithm-implementation-in-python-5ab67bb124a6

parent1_idx = k%parents.shape[0]


右侧将返回什么?
这种表达的名字是什么?
提前致谢 !

最佳答案

我在提到的文章的这段代码中看到了这一行:

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]


其中parents定义如下:

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


从上面的两行中,很明显kparents.shape[0]都是整数,因此这行是两个数值变量之间的简单modulo operatora = b % c

10-06 12:29